Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout with requirejs and underscore to get external templating

I am trying to build a small application using knockout, require, underscore.

I have my index page where i call in require and it points to a main.js were i keep my config

require.config({

paths: {
    jquery:     'vendor/jqm/jquery_1.7_min',
    knockout: 'vendor/knockout/knockout-2.2.0',
    underscore : 'vendor/underscore/underscore_amd',
    text:       'vendor/require/text',
    templates:  '../templates'
}

});

define(['app'], function(app) {

});

the rest of my index has no body. so when this is loaded it calls app.js

define(['jquery','knockout', 'appViewModel'],
 function($, ko, appViewModel) 
{
    ko.applyBindings(new appViewModel());
});

this should then call appViewModel which works ok. This is where i get a bit confused as i then want to load in a template from appViewModel

so I am trying to do something like this

define(['jquery','knockout', 'text!templates/homeViewTemplate.html', 'jqm'],
function($, ko, homeViewTemplate) {

      //call and load in template

});

this is where i get a bit stuck I know in backbone for example I could use

  template:_.template(homeViewTemplate)

but I am really not sure the best way of loading a template in here

I have looked at https://github.com/ifandelse/Knockout.js-External-Template-Engine but this doesnt work very well with require and if you use it without require and just put some text in a html file and call that in when I use jQuery mobile it doesnt add the classes etc.

I wondered if anyone could point me in the right direction.. I guess I am really trying to work out what code to put in here

    define(['jquery','knockout', 'text!templates/homeViewTemplate.html', 'jqm'],
function($, ko, homeViewTemplate) {

      //call and load in template

});

to call in the homeviewtemplate.

thanks

like image 750
Dan Avatar asked Nov 03 '22 10:11

Dan


1 Answers

I use jQuery to insert the template HTML into the page and then apply my Knockout bindings.

$('#selector').append(homeViewTemplate);
ko.applyBindings(VIEWMODEL, $('#selector')[0]);

You may also be interested in my WIP article about advanced knockout binding.

like image 135
Mike B Avatar answered Nov 09 '22 13:11

Mike B