Last active
August 29, 2015 14:08
-
-
Save KOVIKO/d8370a707ed270364bff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
"use strict"; | |
function buildTemplate(data) { // Build the template (you should use a microtemplating engine) | |
return "<div>" + data.toString() + "</div>"; | |
} | |
var Feed = function (url) { | |
this.events = {}; | |
this.url = url; | |
this.items = {}; | |
}; | |
$.extend(Feed.prototype, { | |
onAppend: function (callback, context) { | |
this.bind("append", callback, context); | |
}, | |
onRemove: function (callback, context) { | |
this.bind("remove", callback, context); | |
}, | |
init: function () { | |
this.offset = 0; | |
this.get(10); | |
}, | |
bind: function (eventType, callback, context) { | |
if (!this.events.hasOwnProperty(eventType)) { | |
this.events[eventType] = []; | |
} | |
this.events[eventType].push({ | |
callback: callback, | |
context: context | |
}); | |
}, | |
trigger: function (eventType, data) { | |
var i; | |
if (this.events.hasOwnProperty(eventType)) { | |
for (i = 0; i < this.events[eventType].length; i++) { | |
this.events[eventType][i].callback.call(this.events[eventType][i].context, data); | |
} | |
} | |
}, | |
get: function (count) { | |
var self = this, | |
i; | |
$.ajax({ | |
url: this.url + "?count=" + count + "&offset=" + this.offset, | |
success: function (data) { | |
if ($.isArray(data)) { | |
for (i = 0; i < data.length; i++) { | |
if (data.hasOwnProperty("id")) { | |
self.items[data.id] = data[i]; | |
self.trigger("append", data[i]); | |
} | |
} | |
self.offset += data.length; | |
} | |
} | |
}); | |
} | |
}); | |
$(function () { | |
var myFeed = new Feed(document.location.href), | |
feedDisplay = $("#feed"); | |
myFeed.init(); | |
feedDisplay.items = {}; | |
myFeed.onAppend(function (itemData) { | |
if (itemData.hasOwnProperty("id")) { | |
feedDisplay.items[itemData.id] = $(buildTemplate(itemData)); | |
feedDisplay.append(feedDisplay.items[itemData.id]); | |
} | |
}); | |
myFeed.onRemove(function (itemData) { | |
if (itemData.hasOwnProperty("id") && feedDisplay.items.hasOwnProperty(itemData.id)) { | |
feedDisplay.items[itemData.id].remove(); | |
delete feedDisplay.items[itemData.id]; | |
} | |
}); | |
}); | |
}(window.jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment