Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the Id of model corresponding to clicked item?

How to know the Id of item I clicked? my code is given below:

$(function() {
  ipl.mvc.view.openings_view = ipl.mvc.view.view_base.extend({
    template: '/assets/t/plmt/companies.tmpl.html',
    ID: '#tmpl_openings',
    events: {
      "click #edit": "editpost"
    },
    initialize: function() {
      var _this = this;
      _.bindAll(this, 'addOne', 'addAll', 'render', 'editpost');
      _this.loadTemplate(_this.template, function() {
        _this.model = new ipl.mvc.model.companies_model([]);
        _this.model.view = _this;
        _this.model.bind('change', _this.render, _this);

      });
    }

    ,
    render: function() {
      var _this = this
      jsonData = _this.model.toJSON();
      _.each(jsonData, function(model) {
        $(_this.ID).tmpl(model).appendTo(_this.el);
        return _this;
      });
    }
    ,
    editpost: function(e) {
      console.log("EDIT CLICKED");
      e.preventDefault();
      var ele = $(e.target);
      console.log(ele);
      _this.model = new ipl.mvc.collection.companies_collection([]);
      var id = _this.model.get("id");
      alert(id);
    }
  });
});

and template

<a href="!/editpost/${id}" data-id="${id}"><button id="edit"  ><img   src="/assets/img/pencil.png" /></button></a>

I need id to use in edit function, but not getting ${id} from template, and I follow those steps and I didn't get it? how to get the ${id} of clicked item from template?

like image 846
Venkatesh Bachu Avatar asked Mar 05 '12 08:03

Venkatesh Bachu


1 Answers

actually what you need is this:

  1. you have set the data-id on the html element in the template

  2. you added a method to be executed on the right event (editPost)

  3. in that editPost method you can do this:

    editPost: function(e){
      e.preventDefault();
      var id = $(e.currentTarget).data("id");
      var item = this.collection.get(id);
    }
    

remark i noticed your code has too many closing tags, so it won't run here, and i also noticed in your editPost you try _this but you never declare _this. you should have had var _this = this; in that method.

remark 2 i don't understand why you even need a data-id in this example, there are two ways of rendering a view, either the view has a collection bound to it, or it has a model. When binding a collection to a view, you might somehow need to get the correct id from the element clicked to find the right model in your collection

but on your example, your view has a model bound to it, so you only have that 1 ID, which you can just get by calling this.model.get('id'); i believe your entire code example from above, is copied from another example where they use a collection in the view, since both your rendering, and the use of the data-id property suggests this.

like image 118
Sander Avatar answered Oct 04 '22 04:10

Sander