user2504831
user2504831

Reputation: 157

Backbone JS - get attributes

I'm a new learner on Backbone JS and met a problem.

I have a button on the webpage. After the button is clicked, the attribute "msg" will output on

<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>

But the debugger shows that there is a problem on $("#d").append(model.get('msg'));

How can I solve it? Thanks!

Upvotes: 2

Views: 211

Answers (2)

Ulug&#39;bek
Ulug&#39;bek

Reputation: 2832

@Loamhoof's answer is right. You know when you write

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

here your model will be like a e (event), the event of click #b

Upvotes: 1

Loamhoof
Loamhoof

Reputation: 8293

outputMsg won't receive your model as an argument. You need to give a reference to your model when you instantiate your view. Also, you didn't instantiate any model. So...

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

Upvotes: 1

Related Questions