Backbone JS - 获取属性

时间:2013-06-20 11:04:17

标签: javascript html backbone.js

我是Backbone JS的新学员并遇到了问题。

我在网页上有一个按钮。单击按钮后,属性“msg”将在

上输出
<script>
    var m = Backbone.Model.extend({
        initialize: function(options){
            console.log("A view item is created");
        },
        default: function(){
            return{
                msg: "hello world",
                num: 1000
            };
        }
    });

    var v = Backbone.View.extend({
        el: $("body"),
        events: {
            "click #b": "outputMsg"
        },
        outputMsg: function(model){
            $("#d").append(model.get('msg'));
        }
    });

    var test = new v;
</script>

但调试器显示$(“#d”)存在问题.adndnd(model.get('msg'));

我该如何解决?谢谢!

2 个答案:

答案 0 :(得分:1)

outputMsg不会将您的模型作为参数接收。在实例化视图时,需要提供对模型的引用。此外,您没有实例化任何模型。所以......

var v = Backbone.View.extend({
    el: $("body"),
    events: {
        "click #b": "outputMsg"
    },
    outputMsg: function(){
        this.$("#d").append(this.model.get('msg')); // get the model with this.model
        // also, use this.$, the scoped version of $: http://backbonejs.org/#View-dollar
    }
});

var test = new v({model: new m}); // give a reference to a model to your view

答案 1 :(得分:1)

@ Loamhoof的回答是对的。你知道什么时候写

outputMsg: function(model){
    $("#d").append(model.get('msg'));
}

此处您的model将像e(事件),点击#b