В настоящее время я изучаю backbone.js и задаюсь вопросом об удалении элемента из серии. Я работаю над позорным рецептом и создаю пошаговые инструкции в текстовых областях. Я хочу иметь возможность удалить одно текстовое поле, не удаляя все из них. событие создания выглядит так:
"click #btnAddDirection": "addNewDirection"
addNewDirection: function (ev) {
ev.preventDefault();
this.directionCount++;
this.render(this.directionCount);
},
и мой снимок выглядит так:
'click .subDirection': 'subDirection'
subDirection: function () {
this.$el.remove();
}
проблема в том, что когда я нажимаю кнопку [-], все направления удаляются, а не один. Я думаю, мне нужно передать какой-то идентификатор для направления. Любая помощь будет оценена по достоинству. Благодарю.
вот весь вид управления режимом:
// The Direction Control View
var DirectionControl = Backbone.View.extend({
render: function (directionCount) {
if (directionCount == null) {
directionCount = 1;
}
var that = this;
var directions = new Directions();
var completeDirections = _.invoke(directions, 'fetch');
$.when.apply($, completeDirections).done(function () {
var template = _.template($('#direction-control-template').html(), { directions: directions.models, directionCount: directionCount });
$('.tblDirections').each(function () {
$(this).find('.addDirection').remove();
$(this).find('.newDirection').text('');
});
$(that.$el).append(template);
});
},
events: {
"click #btnAddDirection": "addNewDirection",
'click .subDirection': 'subDirection'
},
directionCount: 1,
addNewDirection: function (ev) {
ev.preventDefault();
this.directionCount++;
this.render(this.directionCount);
},
subDirection: function () {
this.$el.remove();
}
});
что в конечном итоге работало над тем, чтобы добавить индекс данных к элементу таким образом.
<!--Table for Direction entry control -->
<script type="text/template" id="direction-control-template">
<table class="tblDirections" id="idx_<%= directionCount %>">
<tr>
<td class="Directionlabel">Step # <%= directionCount %><input type="hidden" name="DirectionStep" value="1" />:</td>
<td class="Direction"><textarea id="Direction" rows="5" cols="70"></textarea><br></td>
<td>
<button type="button" id="btnAddDirection" class="btn btn-success btn-xs addDirection">+</button>
<button type="button" id="btnSubDirection" class="btn btn-danger btn-xs subDirection" data-index="idx_<%= directionCount %>">-</button>
</td>
</tr>
</table>
</script>
элемент управления выглядит следующим образом:
subDirection: function (ev) {
ev.preventDefault();
var currentTarget = $(ev.currentTarget);
var idx = currentTarget.data("index");
console.log("got index of " + idx);
$("#" + idx).remove();
Лучшей практикой в этой ситуации было бы дать каждому направлению свой индивидуальный вид. Затем, если вы создаете событие в представлении "Направление", оно будет срабатывать только для элементов в этом представлении.
При обратном вызове после того, как маршруты будут получены, вы можете попытаться выполнить циклический переход по directions
и создать новое представление DirectionView:
DirectionView = Backbone.View.extend({
events: {/*put click events for the individual direction here*/}
render: function(){/*render to this.el */ return this}
})
после создания нового DirectionView вы можете отобразить его на основном представлении, которое у вас уже есть:
$(that.$el).append(directionView.render().el);
Функция subDirection
получит объект event
в parameters-, который вы можете использовать для удаления правильного направления. Я предлагаю добавить id
для каждого направления, но если вас не беспокоят дубликаты, вы можете просто притвориться, что содержание направления - это id
. Пример:
subDirection: function(event){
var $direction = $( event.currentTarget ).siblings('.direction-container');
var directionId = $direction.text();
// loop through the model directions until you find the corresponding direction
// then remove that from the directions array
this.render(); // re-render the view
}
Это скорее решение jQuery-esque, а не передовая практика Backbone, например, @Kyle R, но это выполнит то, что вы ищете.