The simplest example of Knockback js working with a RESTful webservice such as ServiceStack?
Asked Answered
R

2

7

I am looking for a VERY simple example that shows wiring up Knockback code to a backbone model that connects via RESTful service. I am using ServiceStack|c# backend. All of the links below are too complicated and use localStore rather than a RESTful service via url. I also prefer to see examples in Javascript not CoffeeScript.

My example url is something like localhost/entities where hitting this will cause the RESTful webservice to return all of the entities. Hitting it with localhost/entity/1 would return the entity with an Id of 1.

_http://kmalakoff.github.com/knockback/index.html

_https://github.com/kmalakoff/knockback-reference-app/

_https://github.com/addyosmani/todomvc

The following is the example from knockback tutorial on the first link:

Models, Collection, ViewModel, and Bindings:
// Generated by CoffeeScript 1.3.3
var model, view_model;

model = new Backbone.Model({
  first_name: "Planet",
  last_name: "Earth"
});

view_model = kb.viewModel(model);

view_model.full_name = ko.computed((function() {
  return "" + (this.first_name()) + " " + (this.last_name());
}), view_model);

ko.applyBindings(view_model, $('#kb_view_model_computed')[0]);

But there is no mention of how you would wire the backbone model up to your RESTful webservice.

There are examples of how do this via Backbone but I am uncertain as to how things change when using Knockback.

The following links were found, but not helpful:

_http://stackoverflow.com/questions/7992431/using-knockoutjs-backbone-together

_https://mcmap.net/q/457368/-is-knockback-js-production-ready-closed

_https://mcmap.net/q/1635042/-defining-models-on-server-side-when-using-mvvm-with-knockout-js

Thanks in advance for any assistance provided. Btw you don't want hyperlinks you get underscores... ;)

Regicide answered 6/9, 2012 at 17:49 Comment(1)
You can use knockback.jsDrysalt
R
7

With much help and support from Kevin Malakoff from the great Knockback project I was able to get a small example working! I used the ServiceStack Backbone Todos project as a starting point.

c# file: Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using ServiceStack.Redis;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;

namespace MyApp
{
    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class PersonService : RestServiceBase<Person>
    {
        public static Person kevin = new Person { Id = 1, FirstName = "Kevin", LastName = "Malakoff" };
        public static Person scott = new Person { Id = 2, FirstName = "Scott", LastName = "Idler" };
        public static List<Person> people = new List<Person> { kevin, scott };

        public override object OnGet(Person person)
        {
            if (person.Id != default(int))
                return people[person.Id-1];
            return people;
        }

        public override object OnPost(Person person)
        {
            return base.OnPost(person);
        }

        public override object OnPut(Person person)
        {
            return OnPost(person);
        }

        public override object OnDelete(Person person)
        {
            return base.OnDelete(person);
        }
    }

    public class AppHost : AppHostBase
    {
        public AppHost() : base("MyApp", typeof(PersonService).Assembly) { }

        public override void Configure(Funq.Container container)
        {
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
            Routes
              .Add<Person>("/persons")
              .Add<Person>("/persons/{Id}");
        }
    }

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            new AppHost().Init();
        }
    }
}

html file: default.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>MyApp2</title>
    <script>window.JSON || document.write('<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">\x3C/script>')</script>
    <script src="Scripts/jquery-1.8.0.js" type="text/javascript" ></script>
    <script src="Scripts/knockback-full-stack-0.16.1.js" type="text/javascript" ></script>
    <script src="myapp.js" type="text/javascript" ></script>
  </head>
<body>
    <div id="myapp">
        <div class="title">
            <h1>MyApp</h1>
        </div>
        <div class="content">
            <div id='kb_observable'>
                <p>First name: <input class='text' data-bind="value: firstName" /></p>
                <p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
                <p>Hello, <span data-bind="text: fullName"></span>!</p>
            </div>
            <div id="kb_collection_observable">
                <div data-bind="if: persons">
                    <span>Has Persons</span>
                </div>
                <div data-bind="foreach: persons">
                    <p>First name: <input class='text' data-bind="value: firstName" /></p>
                    <p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

javascript file: myapp.js

$(function() {

//model
var PersonModel = Backbone.Model.extend({ urlRoot: '/MyApp/persons' });
var model = new PersonModel({ id: 1 });
model.fetch();

//viewmodel
var PersonViewModel = function (person) {

    this.firstName = kb.observable(person, 'firstName');
    this.lastName = kb.observable(person, 'lastName');
    this.fullName = ko.computed((function () {
        return "" + (this.firstName()) + " " + (this.lastName());
    }), this);
};
var personViewModel = new PersonViewModel(model);

//binding
ko.applyBindings(personViewModel, $('#kb_observable')[0]);

//model
var PersonsModel = Backbone.Collection.extend({ model: PersonModel, url: '/MyApp/persons' });
var personsModel = new PersonsModel();
personsModel.fetch();

//viewmodel
var PersonsViewModel = function (persons) {
    this.persons = kb.collectionObservable(persons)
};
var personsViewModel = new PersonsViewModel(personsModel);

//binding
ko.applyBindings(personsViewModel, $('#kb_collection_observable')[0]); });
Regicide answered 9/9, 2012 at 20:9 Comment(0)
F
1

I put together a very simple example. It assumes you already know how to use backbone and knockout so this just gives a quick example of how they can be used together

http://coder2.blogspot.com/2013/02/backbonejs-and-knockoutjs.html

Fuse answered 17/2, 2013 at 22:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.