On Github skinofstars / jsmvc
<h1 data-bind="text: title">Page Title</h1> <ul data-bind="foreach: entries"> <li> <p data-bind="text: headline">Item</p> </li> </ul>
$(document).ready(function(){ var binding = ko.applyBindings(new NewsView()); }); function NewsView(){ var self = this; self.title = ko.observable(); self.entries = ko.observableArray([]); var newsUrl = "http://cdnedge.bbc.co.uk/nol/ukfs_news/hi/front_page/ticker.json"; $.getJSON(newsUrl).then(function(data){ self.title(data.name); $.each(data.entries, function(i,entry){ self.entries.push(entry); }); }); }
<div class="container" id="main"> <h1 id="title">Title</h1> <ul id="entries"> <li></li> </ul> </div>
or maybe something like this?
<script type="text/template" id="decorator_template"> <h1><%= decoratorContent.title %></h1> </script> <ul id="entries"> </ul> <script type="text/template" id="entry_template"> <li><%= entry.headline %></li> </script>
var DecoratorContent = Backbone.Model.extend({ defaults: { title: 'Default page title' } }); var Entry = Backbone.Model.extend({ defaults: { headline: 'Default model headline' } }); var Entries = Backbone.Collection.extend({ model: Entry });
var NewsView = Backbone.View.extend({ el: $('body'), initialize: function(){ _.bindAll(this, 'render', 'appendEntry'); var self = this; this.collection = new Entries(); this.decoratorContent = new DecoratorContent(); var newsUrl = "http://cdnedge.bbc.co.uk/nol/ukfs_news/hi/front_page/ticker.json"; $.getJSON(newsUrl).then(function(data){ self.decoratorContent.set({'title': data.name}); _(data.entries).each(function(item){ var entry = new Entry(); entry.set({ headline: item.headline }); self.collection.add(entry); }); self.render(); }); },
... it goes on!
render: function(){ $('h1#title', this.el).text(this.decoratorContent.get('title')); models = this.collection.models; _.each(models, function(item){ this.appendEntry(item); }, this); }, appendEntry: function(item){ $('ul#entries', this.el).append("<li>"+ item.get('headline') +"</li>"); } });
$(document).ready(function(){ var newsView = new NewsView(); });
<html ng-app="News">
<div ng-controller="NewsCtrl"> <h1>News Title</h1> <ul> <li ng-repeat="entry in items"> <p>{{entry.text}}</p> </li> </ul> </div>
angular.module("News", ['ngResource']); // can't actually use ngResource in this app :( function NewsCtrl($scope, $resource){ $scope.title = ''; $scope.items = [{ text: 'basic item' }]; var newsUrl = "http://cdnedge.bbc.co.uk/nol/ukfs_news/hi/front_page/ticker.json"; $.getJSON(newsUrl).then(function(data){ $scope.title = data.name; $.each(data.entries, function(i,entry){ // use $apply as $.getJSON is out of scope $scope.$apply(function(){ $scope.items.push({ text: entry.headline }); }); }); }); }