我有一个Parent
和Child
视图。该Child
视图通过以下方式扩展Parent
事件:
initialize : function() {
// don't overwrite parent's events
this.events = _.extend( {}, ExerciseRowView.prototype.events, this.events);
},
但是,Parent
期望 aParentModel
和Child
期望 a ChildModel
,所以当一个事件传递给 时Parent
,模型就是ChildModel
。如何将Parent
模型设置为与模型不同Child
?
谢谢!
这是来源,根据要求。
ParentView
又名ExerciseRowView
:
var ExerciseRowView = Parse.View.extend( {
tagName : 'div',
className : 'exerciseWrapper',
template : _.template(exerciseElement),
events : {
'click .icon_delete' : 'confirmDelete',
'click .name' : 'showDetailsPopup'
},
confirmDelete : function() {
var that = this;
if(confirm("Are you sure you want to delete this exercise?")) {
this.destroy({
success: function(exercise) {
// log the action
Log.add(Log.ACTION_EXERCISE_DELETED, exercise.get("name"));
that.$el.fadeOut();
}
});
}
},
showDetailsPopup : function() {
(new ExerciseDetailsView({model: (this.model.constructor == Exercise ? this.model : this.model.get("exercise"))})).render();
},
// accept data as a parameter for workoutexercises
render : function(data) {
_.defaults(data, {
exercise: this.model,
Muscle : Muscle,
Equipment : Equipment,
Exercise : Exercise,
Break : Break,
HTMLHelper : HTMLHelper,
User : User
});
$(this.el).html(this.template(data));
return this;
}
});
ChildView
又名WorkoutExerciseRowView
:
var WorkoutExerciseRowView = ExerciseRowView.extend( {
events : {
"click .icon_randomize" : "changeToRandomExercise"
},
initialize : function() {
// don't overwrite parent's events
this.events = _.extend( {}, ExerciseRowView.prototype.events, this.events);
},
render: function() {
// override the template data with workout exercise template data
return ExerciseRowView.prototype.render.call(this, {
workoutExercise : this.model,
exercise : this.model.get("exercise"),
workoutSection : this.model.get("section"),
isEditable : true,
number : this.options.number,
WorkoutExercise : WorkoutExercise,
WorkoutSection : WorkoutSection
});
},
changeToRandomExercise : function(e) {
// pick a random alternative exercise
var newExerciseId;
do {
newExerciseId = _.keys(this.model.get("alternativeExercises"))[ Math.floor(Math.random() * _.keys(this.model.get("alternativeExercises")).length) ];
} while(newExerciseId == this.model.get("exercise").id);
// grab it
var that = this;
(new Parse.Query(Exercise)).get(newExerciseId, {
success: function(exercise) {
// update the workout exercise
that.model.set("exercise", exercise);
// render it
that.render();
}
});
}
});
目前(如您所见),我测试是否this.model.constructor == Exercise
在ExerciseRowView
. 如果不是,我知道我有一个WorkoutExercise
,里面是一个Exercise
,所以我使用this.model.get("exercise")
:
showDetailsPopup : function() {
(new ExerciseDetailsView({model: (this.model.constructor == Exercise ? this.model : this.model.get("exercise"))})).render();
},
不过,这似乎不是最干净的解决方案。