【问题标题】:Backbone templates getting started: How to go from append() to using a template骨干模板入门:如何从 append() 到使用模板
【发布时间】:2013-04-20 23:23:55
【问题描述】:

这是一个关于如何开始使用模板的非常基本的问题。这实际上是我第一次使用骨干网,所以任何关于如何改进我的代码的额外指针都非常感谢:

示例在这里:http://jsfiddle.net/H93Ej/12/

对于以下sn-p:

    addFurnitureLi: function (model) {
        // Add a new piece of furniture to the DOM list
        $("#furniture-list").append("<li>" + model.get('name') + "</li>");
    }

我想从使用append() 改为使用这样的模板:

<script id="furnitureTemplate" type="text/html">

    <li>{{ name }}</li>

</script>

但是我不知道如何将上述脚本模板集成到addFurnitureLi 函数中。另外,我觉得addFurnitureLi 函数本质上是在页面上“渲染” HTML,所以我还有一个问题——该函数与“官方”render 函数有什么区别?

谢谢你教育我!

完整的应用代码如下:

(function($) {

    Furniture = Backbone.Model.extend({
        defaults: {
            "name" : null,
            "quantity" : 1
        }
    });

    Furnitures = Backbone.Collection.extend({       
        initialize: function (models, options) {
            this.bind("add", options.view.addFurnitureLi);
            //Listen for new additions to the collection and call a view function if so
        }
    });

    FurnitureView = Backbone.View.extend({
        el: $("body"),
        initialize: function () {
            this.furnitures = new Furnitures( null, { view: this });
        },
        events: {
            "click .furniture-add":  "addFurnitureModel",
        },
        addFurnitureModel: function (ev) {
            // Add a piece of furniture to the model
            var furnitureName = $(ev.currentTarget).data('name'),
                furnitureModel = new Furniture({ name: furnitureName });

            this.furnitures.add( furnitureModel);   
        },
        addFurnitureLi: function (model) {
            // Add a new piece of furniture to the DOM list
            $("#furniture-list").append("<li>" + model.get('name') + "</li>");
        }
    });


    var furnitureView = new FurnitureView;

})(jQuery);

【问题讨论】:

    标签: jquery backbone.js jquery-templates mustache icanhaz.js


    【解决方案1】:

    繁荣 shakah-lakah。

    假设您的模板脚本的 ID 是 furnitureTemplate

    <script id="furnitureTemplate" type="text/html">
    
        <li>{{ name }}</li>
    
    </script>
    

    这很好用:

     addFurnitureLi: function (model) {
            // Add a new piece of furniture to the DOM list
            $('#furniture-list').append( ich.furnitureTemplate( model.toJSON() ) );
     }
    

    【讨论】:

      猜你喜欢
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多