界面與數(shù)據(jù)分離怎么做

字號:


    1、界面與數(shù)據(jù)的分離,必須體現(xiàn)在代碼上,界面的代碼歸界面的代碼,數(shù)據(jù)的代碼歸數(shù)據(jù)的代碼,兩者必須涇渭分明。
    2、當(dāng)界面需求發(fā)生改變,只需要改寫界面的代碼,并且所改寫的代碼不能影響到數(shù)據(jù)訪問的代碼。
    只有做到這兩者才算界面與數(shù)據(jù)分離。葉小釵同學(xué)讓我上代碼,趁今天還不是很忙,寫下了下面的代碼:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8" />
    <title></title>
    <script src=">
    <script>
    $(function () {
    var Countries = function () { }
    Countries.prototype = {
    _items: [],
    _getData: function (success) {
    var items = [
    { id: 0, name: '中國' },
    { id: 1, name: '日本' },
    { id: 2, name: '美國' }
    ];
    $.extend(this._items, items);
    success(items);
    },
    //Events
    on_selected: $.Callbacks(),
    on_inserted: $.Callbacks(),
    //Methods
    select: function () {
    var self = this;
    this._getData(function (items) {
    self.on_selected.fire({
    sender: self,
    items: items
    });
    });
    },
    insert: function (item) {
    var self = this;
    this._items.push(item);
    self.on_inserted.fire({ sender: self, item: item });
    }
    }
    //=======================================================================
    // 以下為界面代碼,當(dāng)要調(diào)整界面,改這里就行啦~~~
    var countries = new Countries();
    countries.on_selected.add(function (args) {
    $(args.items).each(function () {
    $('#countries').append($('<option>').attr('value', this.id).text(this.name));
    });
    });
    countries.on_inserted.add(function (args) {
    $('#countries').append($('<option selected="selected">').attr('value', args.item.id).text(args.item.name));
    });
    var id = 10;
    $('#btnAdd').click(function () {
    countries.insert({ id: ++id, name: $('#countryName').val() });
    });
    countries.select();
    //=======================================================================
    });
    </script>
    </head>
    <body>
    <select id="countries"></select>
    <div>
    <input id="countryName" /><button id="btnAdd">添加</button>
    </div>
    </body>
    </html>
    代碼是可以直接Copy運行的,界面如下圖:
    
    界面與數(shù)據(jù)分離怎么做? 三聯(lián)
    上面的代碼,真正做到了界面與數(shù)據(jù)的分離:
    1、在數(shù)據(jù)訪問的代碼,沒有一行涉及到UI的,如果有一行,哪怕一行涉及到,都不能算是界面與數(shù)據(jù)分離。(簡單點說,就是數(shù)據(jù)訪問的代碼,不能對UI有依賴)
    2、當(dāng)界面需求發(fā)生變化,只要修改界面的代碼就可以了。
    3、數(shù)據(jù)訪問的代碼會不會發(fā)生變化?一般來說,這個是很少會發(fā)生變化的(相比界面)。假如發(fā)生變化了,需要修改數(shù)據(jù)訪問的代碼,所作的修改并不會影響到界面的代碼。
    關(guān)于代碼,我就不作解釋了,相信有點基礎(chǔ)的同學(xué)都能看懂