【问题标题】:Data binding in javascriptjavascript中的数据绑定
【发布时间】:2014-04-28 19:56:58
【问题描述】:

我正在尝试为个人项目实现一个简单的通知系统,但我陷入了如何将事件绑定到通知以响应用户操作(如接受或拒绝)的问题。

到目前为止,我得到的是一个动态创建的对象。

/* reference to notifications */
var notifications = [];

// the notification object
var Notification = function(travelInfo){
    this.el = $('#notifications_container');
    this.id = Math.random().toString().substring(7);
    this.travelInfo = travelInfo;
    this.read = false;

};


Notification.prototype.init = function(){
    this.addOne();
    this.render();
    this.bindFunctions();
}

/* dynamically created */
    for(var i = 0; i < 10; i++){
        var notification = new Notification(travelInfo);
        notifications.push(notification);
        notification.init();
    }

该对象应该渲染事件并将事件实际绑定到渲染元素,以便独立跟踪每个通知的操作:

// render the view of a notification
Notification.prototype.render = function(){
    var source = $('#notification-template').html();
    var template = Handlebars.compile(source);
    var data = this.travelInfo;
    result = template(data);
    $('#notifications_container').append(result);
}

Notification.prototype.addOne = function(){
    var number = +$('#notifications_indicator').html();
    $('#notifications_indicator').html(number += 1);
}

Notification.prototype.removeOne = function(){
    var number = +$('#notifications_indicator').html();
    $('#notifications_indicator').html(number -= 1);
}

Notification.prototype.alertId= function(){
    alert('the notification with id:' + this.id + ' is accepted');
}

Notification.prototype.bindFunctions = function(){
    var self = this;
    this.el.on('click', 'li .accept', function(){
        self.alertId();
    });
}

我的方法的问题在于,实际上如果我创建 10 个元素,点击事件会触发 10 次,显示 10 个警报。我想知道的是如何实现一个系统,在该系统中我渲染一个元素并将事件绑定到该元素,就像主干将事件绑定到每个视图项的方式一样。我觉得骨干对于我现在需要的东西来说是如此之大,这只是通知系统。我希望你们能帮助我找到一种方法来做到这一点。

【问题讨论】:

  • 你绑定了10次点击事件,你不能绑定到实际被点击的元素吗?如果不是,您是否可以仅查看您是否已绑定到容器一次然后不再绑定?
  • 您尝试将哪些事件绑定到对象。
  • @MuhammadUmer 我想要的是例如当您单击通知中的接受按钮以将对象的读取状态从 false 设置为 true 时绑定一个事件。
  • @JasonGoemaat 其实我想要的也是保持渲染的 DOM 元素与创建的对象的关系,但不知道如何实现它

标签: javascript jquery oop object backbone.js


【解决方案1】:

如果我没看错你的问题,那你有点想多了。

我相信您正在寻找这样的东西:

<div>
<!-- This is where your HTML is -->
<button type="button" data-post-id="10">Delete this post</button>
<button type="button" data-post-id="11">Delete this post</button>
</div>

现在,在您的 onclick 处理程序上:

function handleDeleteClick() {
  // `this` should be a reference to the element.
  postId = this.getAttribute("data-post-id");
  // Do something with postId
}

完成代码...

element.setAttribute("data-post-id", "11");
element.removeAttribute("data-post-id");

【讨论】:

  • 其实我是这么想的,因为每个对象都会带来特定的数据,比如用户名和其他信息,所以我希望这个元素的数据绑定到对象,但是按照你的建议,你可以做类似的事情将每个通知存储在通知数组 ant 中,然后呈现像 data-id="0" 这样的 div 通知,然后在单击处理程序中将该 id 作为单击通知的引用并执行操作,您认为这是一个好的方法吗?
猜你喜欢
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 2012-08-07
  • 2015-07-28
相关资源
最近更新 更多