jquery.view-api

来源:互联网 发布:沉迷网络 大学生 事例 编辑:程序博客网 时间:2024/06/07 23:50

jQuery.View  class     

plugin: jquery/view

download: jQuery.View

test: qunit.html

Source

View provides a uniform interface for using templates with jQuery. Whentemplate enginesregisterthemselves, you are able to:

  • Use views with jQuery extensions after, append,before, html, prepend,replaceWith,text.
  • Template loading from html elements and external files.
  • Synchronous and asynchronous template loading.
  • Deferred Rendering.
  • Template caching.
  • Bundling of processed templates in production builds.
  • Hookup jquery plugins directly in the template.

The GetStarted with jQueryMX has a good walkthrough of $.View.

Use

When using views, you're almost always wanting to insert the results of arendered template into the page. jQuery.View overwrites the jQuery modifiers sousing a view is as easy as:

$("#foo").html('mytemplate.ejs',{message: 'hello world'})

This code:

  • Loads the template a 'mytemplate.ejs'. It might look like:

<h2><%= message%></h2>

  • Renders it with {message: 'hello world'}, resulting in:

<divid='foo'>"<h2>hello world</h2></div>

  • Inserts the result into the foo element. Foo might look like:

<div id='foo'><h2>hello world</h2></div>

jQuery Modifiers

You can use a template with the following jQuery modifiers:

after

$('#bar').after('temp.jaml',{});

append

$('#bar').append('temp.jaml',{});

before

$('#bar').before('temp.jaml',{});

html

$('#bar').html('temp.jaml',{});

prepend

$('#bar').prepend('temp.jaml',{});

replaceWith

$('#bar').replaceWith('temp.jaml',{});

text

$('#bar').text('temp.jaml',{});

You always have to pass a string and an object (or function) for thejQuery modifier to user a template.

Template Locations

View can load from script tags or from files.

From Script Tags

To load from a script tag, create a script tag with your template and anid like:

<script type='text/ejs' id='recipes'>

<% for(var i=0; i < recipes.length; i++){ %>

 <li><%=recipes[i].name %></li>

<%} %>

</script>

Render with this template like:

$("#foo").html('recipes',recipeData)

Notice we passed the id of the element we want to render.

From File

You can pass the path of a template file location like:

$("#foo").html('templates/recipes.ejs',recipeData)

However, you typically want to make the template work from whatever pagethey are called from. To do this, use // to look up templates from JMVC root:

$("#foo").html('//app/views/recipes.ejs',recipeData)

Finally, the controller/viewplugin can make looking up a thread (and adding helpers) even easier:

$("#foo").html( this.view('recipes', recipeData) )

Packaging Templates

If you're making heavy use of templates, you want to organize them infiles so they can be reused between pages and applications.

But, this organization would come at a high price if the browser has toretrieve each template individually. The additional HTTP requests would slowdown your app.

Fortunately, [steal.static.views steal.views] can build templates intoyour production files. You just have to point to the view file like:

steal.views('path/to/the/view.ejs');

Asynchronous

By default, retrieving requests is done synchronously. This is finebecause StealJS packages view templates with your JS download.

However, some people might not be using StealJS or want to delay loadingtemplates until necessary. If you have the need, you can provide a callbackparamter like:

$("#foo").html('recipes',recipeData, function(result){

 this.fadeIn()

});

The callback function will be called with the result of the renderedtemplate and 'this' will be set to the original jQuery object.

Deferreds (3.0.6)

If you pass deferreds to $.View or any of the jQuery modifiers, the viewwill wait until all deferreds resolve before rendering the view. This makes ita one-liner to make a request and use the result to render a template.

The following makes a request for todos in parallel with the todos.ejstemplate. Once todos and template have been loaded, it with render the viewwith the todos.

$('#todos').html("todos.ejs",Todo.findAll());

Just Render Templates

Sometimes, you just want to get the result of a rendered template withoutinserting it, you can do this with $.View:

var out = $.View('path/to/template.jaml',{});

Preloading Templates

You can preload templates asynchronously like:

$.get('path/to/template.jaml',{},function(){},'view');

Supported Template Engines

JavaScriptMVC comes with the following template languages:

  • EmbeddedJS

<h2><%= message%></h2>

  • JAML

h2(data.message);

  • Micro

<h2>{%= message%}</h2>

  • jQuery.Tmpl

<h2>${message}</h2>

The popular Mustachetemplate engine is supported in a 2nd party plugin.

Using other Template Engines

It's easy to integrate your favorite template into $.View and Steal. Readhow injQuery.View.register.

Constructor

Looks up a template, processes it, caches it, then renders the template withdata and optional helpers.

With StealJS,views are typically bundled in the production build. This makes it ok to useviews synchronously like:

$.View("//myplugin/views/init.ejs",{message: "HelloWorld"})

If you aren't using StealJS, it's best to use views asynchronously like:

$.View("//myplugin/views/init.ejs",

       {message: "Hello World"}, function(result){

 // do something with result

})

new $.View(view, data, helpers, callback) -> String

view {String}

The url or id of an element to use as the template's source.

data {Object}

The data to be passed to the view.

helpers {optional:Object}

Optional helper functions the view might use. Not all templates supporthelpers.

callback {optional:Object}

Optional callback function. If present, the template is retrievedasynchronously. This is a good idea if you aren't compressing the templatesinto your view.

returns {String}

The rendered result of the view or if deferreds are passed, a deferredthat will resolve to the rendered result of the view.

Using Deferreds with Views  page    

jQuery 1.6 brought Deferred support.They are a great feature that promise to make a lot of asynchronousfunctionality easier to write and manage. jQuery.View uses Deferreds tosimplify a common but annoying task into a one-liner: loading data and atemplate and rendering the result into an element.

Templates Consume Deferreds

Here's what rendering templates looks like with deferreds:

$('#todos').html('temps/todos.ejs', $.get('/todos',{},'json') );

This will make two parallel ajax requests. One request ismade for the template attemps/todos.ejs:

<% for(var i =0; i < this.length; i++) { %>
  <li><%= this[i].name %></li>
<% } %>

The second request for /todos might respondwith a JSON array:

[
    {"id" : 1, "name": "Take out the Trash"},
    {"id" : 2, "name": "Do the Laundry"}
]

When both have been loaded, the template is rendered withthe todos data. The resulting HTML is placed in the#todoselement.

This is fab fast! The AJAX and template request are made inparallel and rendered when both are complete. Before deferreds, this was a lotuglier:

var template,
    data,
    done = function(){ 
       if( template && data ) { 
         var html = new EJS({text: template})
                                .render(data);
         $('#todos').html( html )
       }
    }
$.get('temps/todos.ejs', function(text){
  template = text;
  done();
},'text')
$.get('/todos',{}, function(json){
  data = json
  done();
},'json')

Models Return Deferreds

Model AJAX functions now return deferreds. Creating modelslike:

$.Model('User',{
  findAll: '/users'
},{});
 
$.Model('Todo',{
  findAll: '/todos'
},{})

Lets you request todos and users and get back a deferredthat can be used in functions that accept deferreds like $.when:

$.when( User.findAll(), 
        Todo.findAll() )

Or $.View:

$('#content').html('temps/content.ejs',{
  users : User.findAll(),
  todos: Todo.findAll()
})

Jaml  class     

plugin: jquery/view/jaml

Source

Jaml is a simple JavaScript library which makes HTML generation easy andpleasurable.

Instead of magic tags, Jaml is pure JS. It looks like:

function(data) {

 h3(data.message);

}

Jaml is integrated into jQuery.View so you can use it like:

$("#foo").html('//app/views/template.jaml',{});

Use

For more info check out:

  • introduction
  • examples

·        Jaml.register function     

·        Source

·        Registers atemplate by name

·        API

·        Jaml.register(name, template) -> undefined

·        name {String}

·        The name of thetemplate

·        template {Function}

·        The templatefunction

·        returns {undefined}

·        Jaml.registerHelper function     

·        Source

·        Registers a helperfunction

·        API

·        Jaml.registerHelper(name, helperFn) -> undefined

·        name {String}

·        The name of thehelper

·        helperFn {Function}

·        The helper function

·        returns {undefined}

·        Jaml.render function     

·        Source

·        Renders the giventemplate name with an optional data object

·        API

·        Jaml.render(name, data) -> undefined

·        name {String}

·        The name of thetemplate to render

·        data {Object}

·        Optional dataobject

·        returns {undefined}

jQuery.EJS  class     

plugin: jquery/view/ejs

download: jQuery.EJS

test: qunit.html

Source

Ejs provides ERB style clientside templates. Use them with controllers to easily build html and inject itinto the DOM.

Example

The following generates a list of tasks:

<ul>
<% for(var i = 0; i < tasks.length; i++){ %>
    <li class="task <%= tasks[i].identity %>"><%= tasks[i].name %></li>
<% } %>
</ul>

For the following examples, we assume this view is in 'views\tasks\list.ejs'.

Use

Loading and Rendering EJS:

You should use EJS through the helper functions jQuery.Viewprovides such as:

  • after
  • append
  • before
  • html,
  • prepend,
  • replaceWith, and
  • text.

or jQuery.Controller.prototype.view.

Syntax

EJS uses 5 types of tags:

·        <% CODE %> - Runs JS Code. For example:

·         <% alert('hello world') %>

·        <%= CODE %> - Runs JS Code and writes the escaped result into the result of thetemplate. For example:

·         <h1><%= 'hello world' %></h1>

·        <%== CODE %> - Runs JS Code and writes the unescaped result into the result of thetemplate. For example:

·         <h1><%== '<span>hello world</span>' %></h1>

·        <%%= CODE %> - Writes <%= CODE %> to the result of the template. This isvery useful for generators.

·         <%%= 'hello world' %>

·        <%# CODE %> - Used for comments. This does nothing.

·         <%# 'hello world' %>

Hooking up controllers

After drawing some html, you often want to add otherwidgets and plugins inside that html. View makes this easy. You just have toreturn the Contoller class you want to be hooked up.

<ul <%= Mxui.Tabs%>>...<ul>

You can even hook up multiple controllers:

<ul <%= [Mxui.Tabs, Mxui.Filler]%>>...<ul>

To hook up a controller with options or any other jQueryplugin use the pluginview helper:

<ul <%= plugin('mxui_tabs', { option: 'value' }) %>>...<ul>

Don't add a semicolon when using view helpers.

View Helpers

View Helpers return html code. View by default only comeswith viewand [jQuery.EJS.Helpers.prototype.text text]. You can include more with theview/helpers plugin. But, you can easily make your own! Learn how in theHelperspage.

Constructor

Creates a new view

new $.EJS(options) -> jquery.ejs

 {Object}

A hash with the following options

Option

Default

Description

text

 

uses the provided text as the template. Example:
new View({text: '<%=user%>'})

type

'<'

type of magic tags. Options are '<' or '['

name

the element ID or url

an optional name that is used for caching.

 {jquery.ejs}

jQuery.EJS.Helpers  class     

Source

By adding functions to jQuery.EJS.Helpers.prototype, those functions willbe available in the views.

The following helper converts a given string to upper case:

$.EJS.Helpers.prototype.toUpper =function(params)

{

    return params.toUpperCase();

}

Use it like this in any EJS template:

<%= toUpper('javascriptmvc') %>

To access the current DOM element return a function that takes the elementas a parameter:

$.EJS.Helpers.prototype.upperHtml= function(params)

{

    return function(el) {

        $(el).html(params.toUpperCase());

    }

}

In your EJS view you can then call the helper on an element tag:

<div <%= upperHtml('javascriptmvc') %>></div>

Constructor

Creates a view helper. This function is called internally. You shouldnever call it.

new $.EJS.Helpers(data) -> jquery.ejs.helpers

data {Object}

The data passed to the view. Helpers have access to it through this._data

returns {jquery.ejs.helpers}

jQuery.EJS.Helpers.prototype.plugin  function    

Source

Hooks up a jQuery plugin on.

API

ejs.helpers.plugin(name) ->undefined

name {String}

the plugin name

returns {undefined}

jQuery.EJS.Helpers.prototype.view  function    

Source

Renders a partial view. This is deprecated in favor of $.View().

API

ejs.helpers.view(url, data,helpers) -> undefined

url {}

data {}

helpers {}

returns {undefined}

jQuery.EJS.prototype.render  function     

Source

Renders an object with view helpers attached to the view.

new EJS({text: "<%= message%>"}).render({

 message: "foo"

},{helper: function(){ ... }})

API

ejs.render(object, extraHelpers)-> String

object {Object}

data to be rendered

extraHelpers {optional:Object}

an object with view helpers

returns {String}

returns the result of the string

jQuery.EJS.static.clean  function     

Source

Escapes the text provided as html if it's a string.
Otherwise, the value is passed to EJS.text(text).

API

$.EJS.clean(text) -> String

text {String|Object|Array|Function}

to escape. Otherwise, the result of jQuery.EJS.textis returned.

returns {String}

the escaped text or likely a $.View data-view-id attribute.

jQuery.EJS.static.options  attribute     

Source

Sets default options for all views.

$.EJS.options.type = '['

Only one option is currently supported: type.

Type is the left hand magic tag.

jQuery.EJS.static.text  function     

Source

Used to convert what's in <%= %> magic tags to a string to beinserted in the rendered output.

Typically, it's a string, and the string is just inserted. However, ifit's a function or an object with a hookup method, it can potentially be be ranon the element after it's inserted into the page.

This is a very nice way of adding functionality through the view. Usuallythis is done withjQuery.EJS.Helpers.prototype.pluginbut the following fades in the div element after it has been inserted:

<%= function(el){$(el).fadeIn()}%>

API

$.EJS.text(input) -> String

input {String|Object|Function}

the value in between the write magic tags: <%= %>

returns {String}

returns the content to be added to the rendered output. The content isdifferent depending on the type:

  • string - the original string
  • null or undefined - the empty string ""
  • an object with a hookup method - the attribute "data-view-id='XX'", where XX is a hookup number for jQuery.View
  • a function - the attribute "data-view-id='XX'", where XX is a hookup number for jQuery.View
  • an array - the attribute "data-view-id='XX'", where XX is a hookup number for jQuery.View

·        jQuery.fn.after function     

·        Source

·        Extending theoriginal jQuery().after() to render jQuery.Viewtemplates inserted after each element in the set of matched elements.

·        $('#test').after('path/to/template.ejs', { name : 'javascriptmvc' });

·        API

·        $.fn.after(content, data)

·        content {String|Object|Function}

·        A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.

·        data {optional:Object}

·        The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).

·        jQuery.fn.append function     

·        Source

·        Extending theoriginal jQuery().append() torender jQuery.Viewtemplates inserted at the end of each element in the set of matched elements.

·        $('#test').append('path/to/template.ejs', { name : 'javascriptmvc' });

·        API

·        $.fn.append(content, data)

·        content {String|Object|Function}

·        A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.

·        data {optional:Object}

·        The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).

·        jQuery.fn.before function     

·        Source

·        Extending theoriginal jQuery().before() torender jQuery.Viewtemplates inserted before each element in the set of matched elements.

·        $('#test').before('path/to/template.ejs', { name : 'javascriptmvc' });

·        API

·        $.fn.before(content, data)

·        content {String|Object|Function}

·        A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.

·        data {optional:Object}

·        The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).

·        jQuery.fn.html function     

·        Source

·        Extending theoriginal jQuery().html() to render jQuery.Viewtemplates as the content of each matched element.

·        $('#test').html('path/to/template.ejs', { name : 'javascriptmvc' });

·        API

·        $.fn.html(content, data)

·        content {String|Object|Function}

·        A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.

·        data {optional:Object}

·        The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).

·        jQuery.fn.prepend function     

·        Source

·        Extending theoriginal jQuery().prepend() torender jQuery.Viewtemplates inserted at the beginning of each element in the set of matchedelements.

·        $('#test').prepend('path/to/template.ejs', { name : 'javascriptmvc' });

·        API

·        $.fn.prepend(content, data)

·        content {String|Object|Function}

·        A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.

·        data {optional:Object}

·        The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).

·        jQuery.fn.replaceWith function     

·        Source

·        Extending theoriginal jQuery().replaceWith()to render jQuery.Viewtemplates replacing each element in the set of matched elements.

·        $('#test').replaceWith('path/to/template.ejs', { name : 'javascriptmvc' });

·        API

·        $.fn.replaceWith(content, data)

·        content {String|Object|Function}

·        A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.

·        data {optional:Object}

·        The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).

·        jQuery.fn.text function     

·        Source

·        Extending theoriginal jQuery().text() to render jQuery.Viewtemplates as the content of each matched element. Unlike jQuery.fn.htmljQuery.fn.text also works with XML, escaping the provided string as necessary.

·        $('#test').text('path/to/template.ejs', { name : 'javascriptmvc' });

·        API

·        $.fn.text(content, data)

·        content {String|Object|Function}

·        A templatefilename or the id of a view script tag or a DOM element, array of elements,HTML string, or jQuery object.

·        data {optional:Object}

·        The data to renderthe view with. If rendering a view template this parameter always has to bepresent (use the empty object initializer {} for no data).

·        jQuery.tmpl class     

·        plugin:jquery/view/tmpl

·        Source

·        Provides basictemplating with magic tags that look like:

·        ${value}

·        jQuery.Viewintegrates jQuery.tmpl templates into your build process. You can use ajQuery.tmpl like:

·        $('#area').html('//path/to/template.tmpl',{ data });

·        For moreinformation on jQuery.tmpl read it's documentation.

·        jQuery.View.cache attribute     

·        Source

·        Should the viewsbe cached or reloaded from the server. Defaults to true.

·        jQuery.View.ext attribute     

·        Source

·        The default suffixto use if none is provided in the view's url.
This is set to .ejs by default.

·        jQuery.View.hookup function     

·        Source

·        Registers a hookupfunction that can be called back after the html is put on the page. Typicallythis is handled by the template engine. Currently only EJS supports thisfunctionality.

·        var id = $.View.hookup(function(el){

·               //do something with el

·            }),

·            html = "<div data-view-id='"+id+"'>"

·        $('.foo').html(html);

·        API

·        $.View.hookup(cb, the) -> undefined

·        cb {Function}

·        a callbackfunction to be called with the element

·        the {Number}

·        hookup number

·        returns {undefined}

jQuery.View.register  function     

Source

Registers a template engine to be used with view helpers and compression.

Example

$.View.register({

    suffix : "tmpl",

 plugin : "jquery/view/tmpl",

    renderer: function( id, text ) {

        return function(data){

            returnjQuery.render( text, data );

        }

    },

    script: function( id, text ) {

        var tmpl =$.tmpl(text).toString();

        return "function(data){return ("+

            tmpl+

            ").call(jQuery, jQuery, data); }";

    }

})

Here's what each property does:

  • plugin - the location of the plugin
  • suffix - files that use this suffix will be processed by this template engine
  • renderer - returns a function that will render the template provided by text
  • script - returns a string form of the processed template function.

API

$.View.register(info) ->undefined

info {Object}

a object of method and properties

that enable template integration:

  • plugin - the location of the plugin. EX: 'jquery/view/ejs'
  • suffix - the view extension. EX: 'ejs'
  • script(id, src) - a function that returns a string that when evaluated returns a function that can be used as the render (i.e. have func.call(data, data, helpers) called on it).
  • renderer(id, text) - a function that takes the id of the template and the text of the template and returns a render function.

returns {undefined}

Micro  function     

plugin: jquery/view/micro

Source

A very lightweight template engine. Magic tags look like:

{%= message %}

Micro is integrated in JavaScriptMVC so you can use itlike:

$("#foo").html('//app/views/bar.micro',{});

Pros

  • Very Lightweight

Cons

  • Doesn't handle nested tags.
  • Doesn't handle {%= "%}" %}.
  • More difficult to debug.
  • Removes newlines and tabs.

Use

For more information on micro, see John Resig's write up.

API

Micro(str, data) -> undefined

 {String}

template content.

 {Object}

render's the template with this content.

 {undefined}

 

原创粉丝点击