EzDevInfo.com

todomvc

Helping you select an MV* framework - Todo apps for Backbone.js, Ember.js, AngularJS, and many more TodoMVC helping you select an mv* framework - todo apps for backbone.js, ember.js, angularjs, spine and many more

backbone.js "order" attribute like TodoMVC not incrementing

I'm having difficulty getting a model with an auto-incrementing "order" attribute working in BackboneJS.

For some reason every order gets set to 1. The length of the collection in the nextOrder function is always 0.

Options = _.extend(Options, {
    Models: {
        Profile: Backbone.Model.extend({
            defaults: function() {
                console.log("Defaults");
                return {
                    title: "New Profile",
                    order: Profiles.nextOrder(),
                    active: false
                };
            },
            url: "/youdontcare"
        })
});

Options = _.extend(Options, {
    Collections: {
        ProfileList: Backbone.Collection.extend({
            model: Options.Models.Profile,
            comparator: function(profile) {
                console.log("Comparator");
                return profile.get('order');
            },
            nextOrder: function() {
                console.log("nextOrder...");
                console.log(this.length);
                if (!this.length) return 1;
                return this.last().get('order') + 1;
            },
            url: "/youdontcare"
        })
});

Options = _.extend(Options, {
    Views: {
        ProfileView: Backbone.View.extend({
            tagName: "li",
            template: _.template($('#profile-template').html()),
            render: function() {
                console.log("Render Profile");
                this.$el.html(this.template(this.model.toJSON()));
                return this;
            }
        }),
        ProfileListView: Backbone.View.extend({
            el: $("#auth_env_list"),
            initialize: function() {
                Profiles = new Options.Collections.ProfileList;
                console.log("INIT LIST");

                this.listenTo(Profiles, 'add', this.addOne);
                this.listenTo(Profiles, 'reset', this.addAll);
                this.listenTo(Profiles, 'all', this.render);

                // Suppresses 'add' events with {reset: true} and prevents the app view 
                // from being re-rendered for every model. Only renders when the 'reset'
                // event is triggered at the end of the fetch.
                console.log("Fetching");
                Profiles.fetch({ reset: true });
                console.log("Done fetching");
            },
            addOne: function (profile) {
                console.log("addOne");
                var view = new Options.Views.ProfileView({ model: profile });
                this.$el.append(view.render().el);
            },
            addAll: function () {
                console.log("addAll");
                this.$el.html('');
                Profiles.each(this.addOne, this);
            },
            render: function() {
                console.log("RENDER PROFILE LIST VIEW");

                if (Profiles.length)
                {

                }
            }
        })
});

I can see that the nextOrder function inside the Profiles instance of the Options.Collections.ProfileList collection is called the appropriate number of times for each element that is fetched for the collection... however the length of the collection it tries to compute with this.length always returns 0!

Console output with 5 "Profile" elements:

INIT LIST
Fetching 
RENDER PROFILE LIST VIEW
Done fetching
Defaults
nextOrder... 
0
Defaults
nextOrder...
0
Defaults
nextOrder...
0
Defaults 
nextOrder...
0
Defaults
nextOrder...
0
Comparator 
addAll
addOne
Render Profile
addOne
Render Profile
addOne
Render Profile
addOne
Render Profile
addOne
Render Profile
RENDER PROFILE LIST VIEW
RENDER PROFILE LIST VIEW

Is there a better way I could assign an auto incrementing client side ID to these? The only reason I want to do it is to display them in a numbered list.


Source: (StackOverflow)

Where is the editing of TodoMVC Ember getting saved?

I'm having trouble figuring out where the edit is being saved. It looks like when we make an edit, the edit is going directly into the Local Storage, and saved immediately. But the view's change method has no save() anywhere. Do you know how this magic is getting done?

change: function () {
    var value = this.get('value');

    if (Ember.isEmpty(value)) {
        this.get('controller').removeTodo();
    }
},

I'm looking at the source directly in the chrome source viewing.


Source: (StackOverflow)

Advertisements

TodoMVC app using Backbone.js and SQL Server instead of backbone-localstorage.js

I am learning backbone.js, I have gone through these series of tutorials before : Link1, Link2

Now I am going through TodoMVC using Backbone.js and you can see the code here.

What I want to do

As you can see in the example, the example uses backbone-localstorage.js, now instead of this I want to implement the same thing using ASP.NET MVC, where the values will be stored in a SQL Server database.

I am really confused on how to start about on this, can anyone please guide me on how can I do this.


Source: (StackOverflow)

marionette todomvc extend error

TodoMVC.module "TodoList", (TodoList, App, Backbone, Marionette, $, _) ->

  # TodoList Router
  # ---------------
  #
  # Handle routes to show the active vs complete todo items
  TodoList.Router = Marionette.AppRouter.extend
    appRoutes: "*filter": "filterItems"

  # TodoList Controller (Mediator)
  # ------------------------------
  #
  # Control the workflow and logic that exists at the application
  # level, above the implementation detail of views and models
  TodoList.Controller = ->
    @todoList = new App.Todos.TodoList()

  _.extend TodoList.Controller::,

    # Start the app by showing the appropriate views
    # and fetching the list of todo items, if there are any
    start: ->
      @showHeader @todoList
      @showFooter @todoList
      @showTodoList @todoList
      App.bindTo @todoList, "reset add remove", @toggleFooter, this
      @todoList.fetch()

    showHeader: (todoList) ->
      header = new App.Layout.Header(collection: todoList)
      App.header.show header

    showFooter: (todoList) ->
      footer = new App.Layout.Footer(collection: todoList)
      App.footer.show footer

    showTodoList: (todoList) ->
      App.main.show new TodoList.Views.ListView(collection: todoList)

    toggleFooter: ->
      App.footer.$el.toggle @todoList.length

    # Set the filter to show complete or all items
    filterItems: (filter) ->
      App.vent.trigger "todoList:filter", filter.trim() or ""


  # TodoList Initializer
  # --------------------
  #
  # Get the TodoList up and running by initializing the mediator
  # when the the application is started, pulling in all of the
  # existing Todo items and displaying them.
  TodoList.addInitializer ->
    controller = new TodoList.Controller()
    new TodoList.Router(controller: controller)
    controller.start()

Uncaught NoMethodError: Method 'filterItems' was not found on the controller

I've taken the TodoMVC example for Marionette, and converted it to CoffeeScript using js2coffee and I'm using requirejs. I'm not sure why this is happening, as I've added no real custom code. If there is any additional information I can include, please let me know.


Source: (StackOverflow)

How to create a note like this TodoMvc example

i want to create a note form like this under link using jQuery Html Css Js. http://todomvc.com/examples/flight/

here is my html code:

<form id="myform" action="whatever.php">
    <lable name="text">enter text</label>
    <input id="in" type="text" placeholder="What needs to be done?" />
    <input type="submit" value="Enter" />
</form>

<div class="results">
    <ul class="list">
    </ul>
</div>

here is my jquery:

$( document ).ready(function() {
    $('#myform').submit(function(e){
        var val = $(this).find('#in').val();
        $('ul.list').append('<input id="check" type="checkbox"><p>' + val + '</p>');
        e.preventDefault();
    });

    $('ul.list').on("click", "input", function(){
        if( $(this).is(':checked') ) {
            $(this).next('p').css("text-decoration" ,  "line-through");
        } else {
            $(this).next('p').css("text-decoration", "none");
        }
    });
});

i want:

  1. the checkbox input type and p tag are in same line

  2. add a delete button next to each of the checkbox to delete that note

  3. a button to check all the box and uncheck all


Source: (StackOverflow)

In todomvc backbone example, why use event bind instead of routes in controller?

For example, in app-view.js, I see some event bind:

    events: {
        'keypress #new-todo': 'createOnEnter',
        'click #clear-completed': 'clearCompleted',
        'click #toggle-all': 'toggleAllComplete'
    },

but in my opinion, the routes in controller could replace event bind at all, like:

var TodoRouter = Backbone.Router.extend({
    routes: {
        '*filter': 'setFilter',
         'todo/add': 'add',
         'todo/edit/:id': 'edit',
         'todo/delete/:id': 'delete'
    },
    add: function () {...},
    edit: function () {...},
       ......
});

and just replace the button with link, and I think use routes make it more like a mvc app, just like ASP.NET MVC

Why it still use event bind?


Source: (StackOverflow)

Ember.js how to design different representations of Data (with TodoMVC as an example)?

I would like to know what's the best way of designing the display of different representations of the same data model in Ember.js. To ask my question, I'll use the TodoMVC of Ember.JS, which has 3 representations of todo-data:

  1. any todo, i.e. the entire todo list (TodosIndexRoute)
  2. todos that are still active and incomplete (TodosActiveRoute)
  3. todos that have been completed (TodosCompletedRoute)

Currently, you can see each of the 3 by clicking on the words at the bottom of the list, directing to a different URL each time. Since currently each representation has a route, it makes sense that each representation gets its unique URL. The main page displays the entire todo list (1.).

A. What is the best ember.js design to make the main page display all 3 representations (i.e. under just one URL)?

B. How about the best design that displays all 3 on the main page as well as on separate pages?


Currently I only figured out a clumsy way and made this modified TodoMVC app that shows incomplete and completed lists at the bottom of the page.

In index.html, I added new named lists:

{{#each todosactive itemController="todo"}}
    {{ title }},
{{/each}} 

In the js router, I copied TodosActiveRoute and TodosCompletedRoute into TodoIndexRoute, which is code duplication, very bad.

Todos.TodosIndexRoute = Ember.Route.extend({
    setupController: function () {
        var todos = Todos.Todo.find();
        this.controllerFor('todos').set('filteredTodos', todos);

        var todos_active = Todos.Todo.filter(function (todo) {
            if (!todo.get('isCompleted')) {
                return true;
            }
        });

        this.controllerFor('todos').set('todosactive', todos_active);

        ...
});

I feel like I'm missing an elegant way of doing this, but my current ember.js knowledge is very limited. Should I use {{partial}}, {{render}}, render, or something else?

I tried {{ partial }} and {{ render }}, but I can't get them to display any data .

Thanks for helping out.


Source: (StackOverflow)

EmberJS todoMVC example implementing Parse Data Adapter, duplicate items

I was giving ember.js a try, and it looks really cool, having MVC architecture in javascript. I followed the todoMVC getting started guide, and everything worked perfectly. I replaced the data adapter with the Parse Data Adapter and it seems to work. But for some reason it affects the actual application by creating the same record twice even though it only runs Todos.Todo.createRecord(..) once.

I was under the impression that the data storage shouldn't have an effect on any of the code before it gets pushed to the data storage, but I may need a little bit of help to work out what is going wrong.

Everything is the same as the getting started tutorial apart from the use of the Parse data storage. It works fine using the localstorage adapter though. Any help would be greatly appreciated!

store.js file:

Todos.Store = DS.Store.extend({
    revision: 11,
    adapter: ParseAdapter.create({
      applicationId: '',
      restApiId: '',
      javascriptId: ''//These filled in appropriately. 
    })
});

todo.js file:

Todos.Todo = ParseModel.extend({
    title: DS.attr('string'),
    isCompleted: DS.attr('boolean')
});

Check out the JSbin:

Todo emberjs + Parse with duplicate problem JSBIN.


Source: (StackOverflow)

ember js slight modification on todomvc failure

I'm trying to follow the todomvc tutorial on emberjs getting started documentation to understand it better. In the following stage of the tutorial where we add the editing capability to todo items.

in the following link: http://emberjs.com/guides/getting-started/accepting-edits/

What I did differently from the tutorial is that I turned the todo items into contacts with a title and number. So here is my html addition:

{{edit-contact class="edit" value=title focus-out="acceptChanges" insert-newline="acceptChanges"}}
{{edit-number class="edit" value=number focus-out="acceptChanges" insert-newline="acceptChanges"}}

And here is the addition I made to edit_todo_view.js

Contacts.EditContactView = Ember.TextField.extend({
  didInsertElement: function() {
    this.$().focus();
  }
});

Contacts.EditNumberView = Ember.TextField.extend({
  didInsertElement: function() {
    this.$().focus();
  }
});

Ember.Handlebars.helper('edit-contact', Contacts.EditContactView);
Ember.Handlebars.helper('edit-number', Contacts.EditNumberView);

It gives the following error though:

Uncaught TypeError: Cannot read property 'start' of undefined VM2755: line 971

If I discard either the number or the title from the HTML it works fine.

It also works fine if I debug and put a breakpoint in "this.$().focus();" lines mentioned above.

Any assitance would be greatly appreciated

All the best


Source: (StackOverflow)

how does todo mvc example for angularjs do without ng-controller?

Every example I've looked at has made use of the ng-controller directive to get things working.

The Todo MVC example at https://github.com/tastejs/todomvc/tree/gh-pages/examples/angularjs creates a 'TodoCtrl' controller. But in the corresponding index.html, there is no use of the ng-controller directive.

How is this possible? and why did they choose to do it this way?


Source: (StackOverflow)

In TodoMVC what is data-framework="backbonejs" on the element for?

I found in the index.html of the TodoMVC example the following line of code:

<html lang="en" data-framework="backbonejs">

Does anybody know for this data element is used for?


Source: (StackOverflow)

How do I add Projects parent to Ember-CLI TodoMVC?

I am working on a todo type project using Ember-CLI. I used as a starting point the nifty todoMVC project, but built with Ember-CLI using this guide:

http://blaketv.com/2014/10/03/ember-cli-todo-mvc-tutorial-0-0-47//

My question is, how would I go about adding projects at the parent level. So we would have a master-detail type interface and in the sidebar we would have projects and you could CRUD project names, and then when you click on a project name, you see the todos in the detail pane.

I have gotten far enough defining the hasMany relationships to the models, but I cannot figure out if I need multiple {{outlets}} It is very difficult to get everything on the same page and working.

Here is my model for project:

export default DS.Model.extend({
  title: DS.attr('string'),
  isCompleted: DS.attr('boolean'),
  description: DS.attr('string'),
  todos: DS.hasMany('todo', {async: true})
});

and model for todos:

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  isCompleted: DS.attr('boolean')
});

and the main Router:

Router.map(function() {
  this.resource('projects', function () {
    this.route('new'); 
    this.resource('project', { path: ':id' }, function () {
      this.route('todos');
    });
  });
});

Project Route:

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('project', params.id);
  }
});

Index Route:

export default Ember.Route.extend({
  model: function() {
    return this.store.find('project');
  }
});

Todos Route:

export default Ember.Route.extend({
  model: function() {
    return this.modelFor('todos');
  }
});

So for project.hbs this is where it gets tricky. I create the sidebar with bootsrap and then this outlet shows the todos....

<div class="projects-column col-md-3">
  <div id="inbox-header"><span class="glyphicon glyphicon-inbox"></span> Inbox <span class="badge">42</span></div>
  <div id="projects-header"><span class="glyphicon glyphicon-list-alt"></span> Projects</div>
  <div id="forecast-header"><span class="glyphicon glyphicon-calendar"></span> Forecast</div>
  <div id="log-header"><span class="glyphicon glyphicon-book"></span> Sessions Log</div>
</div>
  <div>{{outlet}}</div>

Index.hbs:

<ul>
  {{#each model}}
  <li>{{link-to title "project.todos" this}}</li>
 {{/each}}

So this above when you click on the project title link, it shows the associated todos.... but it renders in the left pane... it's probably just something about the CSS layout...but something tells me there is a very Ember-ish way to do this that I am missing.

Then in /project/todo.hbs we have the iteration

{{#each model.todos}}
    <li>{{title}}</li>
{{/each}}

I haven't even really addressed making the CRUD for controllers or anything. Most likely this above is laughable and there is a much more elegant way to approach this...

Basically I want a projects parent route, that I do CRUD with... and then when you render a list of project links in the sidebard and click on one, you get in the right pane the rendered ToDoMVC working app.

Of course this is just a starting point for my application. Most likely if someone comes up with a elegant way to do this, we can turn it into an open source project on github for others to learn from.

I think a bunch of burgeoning ember developers are having a hard time with this type of thing because of the multiple ways to do it (outlets, partials, render, render into other templates, views, components, etc)

Don't really know how to get any further.


Source: (StackOverflow)

A learning application for popular web frameworks, like TodoMVC

First of all, to the moderators, don't get angry if this is not the right place to post this :).

I wondre if there is something like the TodoMVC for popular web frameworks like Django, Rails, Symfony and etc.

If there is not something like this, we could create one.

Any ideas? Volunteers?


Source: (StackOverflow)

Extending TodoMVC to support multiple todo lists

I'm trying to get a feel for Ember by extending the standard Todo MVC. I want to introduce the concept of multiple todo lists (eg shopping list, reading list etc)

My code is online: http://jsbin.com/qidag/1/edit (I get slightly different/more verbose errors when not running inside jsbin)

In the browser, I create a couple of lists. Then when I try and visit a list I get an Ember error:

Error while loading route: Error: Assertion Failed: ArrayProxy expects an Array or Ember.ArrayProxy, but you passed object

If I try and click the route again, the todos load like they are supposed to. Then if I try and click any other link to load a different list, I get an error:

Error while loading route: TypeError: undefined is not a function

When I refresh on the route, the list loads without errors.

Can anyone enlighten me: why do I get different errors depending on how I visit the route? Have I missed some magic that ember does behind the scenes?

Secondly, my code doesn't work! The errors start appearing when I define my TodosController explicitly as an ArrayController rather that the controller ember generates. It feels like I'm missing a relationship - I've tried explicitly setting the itemController property and changing Route.map() (routes VS resources etc) but I can't get passed the "object being passed to ArrayProxy" error!

If someone could propose a solution or point me to the relevant docs, I'd be super grateful! Thanks Scazz


Source: (StackOverflow)

TodoMVC with ember, id does not increment

I am following the getting started guide from emberjs, and am at the point where I can add todos. My problem is though that when I add a todo it has an id value of null - is there a practical way to auto increment this?

var TodosController = Ember.ArrayController.extend({
actions: {
    createTodo: function() {
        var title = this.get('newTitle');
        if (!title.trim()) {
            return;
        }

        var todo = this.store.createRecord('todo', {
            title: title,
            isCompleted: false
        });

        this.set('newTitle', '');

        todo.save();
    }
}

});


Source: (StackOverflow)