2014/08/11 – Backbonejs

來源:互聯網
上載者:User

標籤:style   blog   http   color   java   使用   os   io   

[來自: Backbone.js 開發秘笈 第6章]

Template 用法:

通過 Underscore.js 提供的 _.template() 方法,我們可使用 <% ... %> 包含js代碼;使用 <%= ... %> 輸出變數值;使用 <%- ... %>輸出轉義後的變數值。

(function ($) {    //define -------------------------    var UserModel = Backbone.Model.extend();    var UserCollection = Backbone.Collection.extend({        model: UserModel    });    var UsersView = Backbone.View.extend({        tagName: ‘ul‘,        //用預設 Underscore 的 _.template() 方法定義模板        template: _.template("<% _.each(users,function(user){%>" +            "<li><a hre=‘javascript:;‘ data-id=‘<%= user.id %>‘><%= user.name %></a></li>"            + "<%}); %>"),        render: function () {            //調用模板對象擷取產生的 HTML            $(this.el).html(this.template({                users: this.collection.toJSON()            }));            return this;        }    });    //instance -----------------------------    var usersView = new UsersView({        collection: new UserCollection([            { id: 1, name: ‘yoyo‘ },            { id: 7, name: ‘ronaldo‘ },            { id: 4, name: ‘ramos‘ }        ])    });    //apply -------------------------------    $(function () {        $(‘body‘).html(usersView.render().el);    });})(jQuery);

1. 模板載入器

模板元素:<script type="text/template" id="userTemplate">...</script>

(function ($, win, undefined) {    $(function () {        //define -------------------------------------------------------        var $templates = {};        $("script[type=‘text/template‘]").each(function () {            $templates[$(this).attr(‘id‘)] = _.template($(this).html());            $(this).remove();        });        $.tempates = $.tempates || $templates;        //apply ---------------------------------------------------------        $(‘body‘).html("<ul>" + $.tempates.userTemplate({ id: 1, name: ‘yoyo‘ }) + "</ul>");    });})(jQuery, window);
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.