H. Adolf H. Adolf - 1 month ago 6
Javascript Question

Backbone.js get clicked link dtat-id and fetch model with that id

Hi yesterday I have post question change Jquery events to Backbone.js events. My question to be similar to the one that I asked yesterday. I hope that I will get the correct answer.

Here is my question

I have backbone.js app I need to get clicked link data-id and same time fetch model with that id.

My model

define(['backbone'], function(Backbone){
var item = Backbone.Model.extend({
url: 'localhost:8080/getitem/'//need here put id to get right item
});
return item;
});


My View

define(['models/itemModel', 'backbone', 'jquery', 'underscore', 'text!templates/itemsTemplate.html'], function(ItemModel, Backbone, $, _, ItemTemplate){
var itemsView = Backbone.View.Extend({
template: _.template(ItemTemplate),
events: {
'click a.item': 'clickedItem'
},

clickedItemL: function(e) {
/*get clicked link data id and fetch it*/
},
render: function(){
var self = this;
self.$el.html(self.template({}));
return this;
}
});
});


Any help much appreciated.

Answer

To achieve you goal you need to change model and view like this.

Model

define(['backbone'], function(Backbone){
    var item = Backbone.Model.extend({
        initialize: function(options){
            this.id = options.id
        },
        url: function(){
            return 'localhost:8080/getitem/'+this.id;
        },
    });
   return item;
});

View

define(['models/itemModel', 'backbone', 'jquery', 'underscore', 'text!templates/itemsTemplate.html'], function(ItemModel, Backbone, $, _, ItemTemplate){
    var itemsView = Backbone.View.Extend({
        template: _.template(ItemTemplate),
        events: {
           'click a.item': 'clickedItem'
        },

        clickedItem: function(event) {
            event.PreventDefault();
            var itemId = $(event.currentTarget).data('id');
            var model = new ItemModel({id: itemId});
            model.fetch({
                success: function(){
                    //success handler 
                },
                error: function(error){
                    //error handler
                },
            });
        },
        render: function(){
            var self = this;
            self.$el.html(self.template({}));
            return this;
        }
    }); 
});

this is it.