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

前端 未结 2 734
青春惊慌失措
青春惊慌失措 2021-01-13 08:04

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

$(function() {
  ipl.mvc.view.openings_view = ipl.mvc.vi         


        
相关标签:
2条回答
  • 2021-01-13 08:45

    This is another (newer versions of backbone?) way of doing this: (I see @Sander shows the model.get method in his remarks)

    var AppointmentView = Backbone.View.extend({
      events: {
        'click' : 'alertTitle'
      },
    
      alertTitle : function(e) {
        // this.model.get('id') is what you're looking for
        alert( this.model.get('title') );
      }
    });
    
    0 讨论(0)
  • 2021-01-13 08:55

    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.

    0 讨论(0)
提交回复
热议问题