var pubsub = Pubsub.create();
function ItemList() {
this.root = $('#container');
}
ItemList.prototype.build = function () {
this.bindAllListener();
};
ItemList.prototype.bindAllListener = function () {
this.root.on('click', '.item-favorite-anchor.selectable', $.proxy(this.addFavorite, this));
};
ItemList.prototype.addFavorite = function (evt) {
var target = $(evt.currentTarget),
itemId = target.data('itemId'),
localContext = pubsub.Context.create();
localContext.subscribe('favorite.added', function () {
alert('favorite added');
target.text('★');
target.removeClass('selectable');
});
pubsub.publish('favorite.icon.clicked', localContext, itemId);
};
function Favorite() {}
Favorite.prototype.exportEvent = function () {
pubsub.subscribe('favorite.icon.clicked', $.proxy(this.add, this));
};
Favorite.prototype.add = function (context, itemId) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
json: itemId,
delay: 1
}
}).then(function () {
context.publish('favorite.added');
});
};
var favorite = new Favorite(),
itemList = new ItemList();
favorite.exportEvent();
itemList.build();
<div id="container">
<div id="item-list">
<div class="item-raw item-first clearfix">
<p class="item-input">
item: apple
</p>
<p class="item-favorite">
<a href="#" class="item-favorite-anchor selectable" title="お気に入りに追加" data-item-id="1">☆</a>
</p>
</div>
<div class="item-raw clearfix">
<p class="item-input">
item: orange
</p>
<p class="item-favorite">
<a href="#" class="item-favorite-anchor selectable" title="お気に入りに追加" data-item-id="2">☆</a>
</p>
</div>
<div class="item-raw clearfix">
<p class="item-input">
item: grape
</p>
<p class="item-favorite">
<a href="#" class="item-favorite-anchor selectable" title="お気に入りに追加" data-item-id="3">☆</a>
</p>
</div>
</div>
</div>
.item-first{
border-top: 6px solid #069;
counter-reset:item;
}
.item-raw{
border-left: 6px solid #069;
border-right: 6px solid #069;
border-bottom: 6px solid #069;
padding: 5px;
height: 2em;
line-height: 2em;
}
.item-input:before {
counter-increment: item;
content: counter(item) ") ";
}
.item-input {float: left;}
.item-favorite{float: right;}
.item-favorite-anchor{
text-decoration: none;
display: block;
color: orange;
text-align: center;
font-weight: bold;
font-size: 20px;
}
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
External resources loaded into this fiddle: