Ember.js - 正确的(结构,包括,一般问题) [英] Ember.js - doing it right (structure, includes, general questions)

查看:97
本文介绍了Ember.js - 正确的(结构,包括,一般问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩ember.js,并以某种方式找到正确的方式来建立结构。我可以遵循所有示例,但将它们全部放在一起的问题。



我正在使用require.js和handlebars。



我的目录结构如下所示:

   -  app 
- - controllers
- - css
- - helpers
- - lib
- - models
- - 路线
- - 模板
- - - 部分
- - 视图

我的application.js如下所示:

  require.config({
paths: {
jquery:'lib / jquery-1.7.2',
handlebars:'lib / handlebars',
ember:'lib / ember',
ember_data:'lib / ember-data',
text:'lib / requireJS / text',
md5:'lib / md5',
spin:'lib / spin'
},

shim:{
'ember':{
deps:['jquery','handlebars'],
exports:'Ember'
},
'ember_data':{
deps:['ember'],
exports:'DS'
}
},

waitSeconds:15
});

define('application'
,[
//路由
'routes / app_router'

//控制器
,'controllers / application_controller'

//视图
,'views / application_view'
,'views / category / category_list_view'

//库
,'jquery'
,'handlebars'
,'ember'
,'ember_data'
,'spin'

]
,函数(

//路由器
路由器

//控制器
,ApplicationController

//视图
,ApplicationView
,CategoryListView

//模型
,类别
,产品

{
返回Ember.Application.create({

VERSION:'1.0.0'

,rootElement:'#main'

//加载路由器
,路由器:路由器

//负载控制器
,ApplicationController:ApplicationController

//加载关联视图
,ApplicationView:ApplicationView
,CategoryListView:CategoryListView

//加载模型
,类别:类别
,产品:Product

//持久层,在ember-data.js中使用默认的RESTAdapter。
,store:DS.Store.create({
revision:10
,adapter:DS.RESTAdapter.create({
bulkCommit:false
,serializer:DS .Serializer.create({
primaryKey:function(type){
return type.pk;
}
})
,映射:{
/ /类别:类别
}
,命名空间:'api'
,url:https://example.org
})
})

,准备好:function(){

}
});
}
);

然后我的应用程序控制器

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 

init:function(){
}
});
}
);

应用程序视图:

  define('views / application_view',[
'text!templates / application.html',
'ember'
],
function(Application_markup ){
return Ember.View.extend({
template:Ember.Handlebars.compile(Application_markup),
elementId:'container',
didInsertElement:function(){
这个$()。hide()。show(slow);
}
});
}
);

最后,application.html模板

 < div id =container> 

< div id =header>
FOO BAR
< / div>

< div id =navigation>
{{outlet mainNavigation}}
< / div>

< div id =content>

< / div>

< div id =footer>

< / div>

< / div>

我现在要做的是将另一个模板包含在主应用程序模板(category_list)中。我想我必须在HTML模板本身或应用程序视图中执行此操作 - 但是在后一种情况下,我不知道如何配置/解析/绑定多个模板。



建立个人,独立,模块化模板并把它们放在一起的最佳做法是什么?这究竟在哪里呢?
或者这甚至是使用ember.js的错误方法?



也许你们中的一个可以让我更清楚一些事情。
谢谢。



编辑#1



app_router.js

  define('routes / app_router',
['ember'],
function(){
return Em.Router .extend({
enableLogging:true,//对开发有用
/ * location属性:'hash':使用URL片段标识符(如#/ blog / 1)进行路由
'历史':使用浏览器的history.pushstate API进行路由,仅适用于具有pushstate支持的现代浏览器
'none':不读取或设置浏览器URL,但仍允许路由发生。 。* /
location:'hash',
/ * location:'history',
rootURL:'/ app',* /
root:Ember.Route.extend {
index:Ember.Route.extend({
route:'/'

/ *,connectOutlets:function(router){
//渲染应用程序查看,登录。
v = router.get('applicationController')。get('view');
if(v)v.remove();
App.router.get('applicationController')。set('loggedin',false);

router.get('applicationController')。connectOutlet({name:'login',outletName:'loginform'});
router.get('loginController')。enterLogin();

} * /
})
/ *,联系人:Em.Route.extend({
route:'/ contacts',

showContact:function(router,event){
router.transitionTo('contacts.contact.index',event.context);
},

showNewContact:function路由器){
router.transitionTo('contacts.newContact',{});
},
logout:function(router){

jQuery.ajax {
url:'/ site / logout',
type:'POST',
success:function(response){
if(!response.authenticated){
router.get('applicationController')。set('loggedin',false).get('view')。remove();
router.transitionTo('root.index',{});
}
}
})
},


索引:Em.Route.extend({
route:' /',
connectOutlets:function(router){
if(router.get('applicationController')。get('loggedin')
router.get('applicationController')connectOutlet ('contacts',App.store.findAll(App.Contact));
else router.transitionTo('root.index');
}
}),

联系人:Em.Route.extend({
route:'/ contact',
index:Em.Route.extend({
route:'/:contact_id',
deserialize:function(router,urlParams){
return App.store.find(App.Contact,urlParams.contact_id);
调试器;
},

showEdit:function(router){
router.transitionTo('contacts.contact.edit');
},

connectOutlets:function(router,context){
if(router.get('applicationController')。get('loggedin')
router .get('contactsController')。connectOutlet('contact',context);
else router.transitionTo('root.index');
}
}),

编辑:Em.Route.extend({
route:'edit',

cancelEdit:function (路由器){
router.transitionTo('contacts.contact.index');
},

connectOutlets:function(router){
if(router。 get('applicationController')get('loggedin'){
var contactsController = router.get('contactsController');
contactsController.connectOutlet('editContact',router.get('contactController' ).get('content'));
router.get('editContactController')。enterEditing();
} else router.transitionTo('root.index');
},

exit:function(router){
router.get('editContactController')。exitEditing();
}
})
}),
newContact:Em.Route.extend({
route:'/ contacts / new',

cancelEdit:function(router){
router.transitionTo('contacts.index');
},

connectOutlets:function(router){
if (router.get('applicationController')。get('loggedin')){
router.get('contactsController')。connectOutlet('editContact',{});
router.get editContactController')enterEditing();
} else router.transitionTo('root.index');
},

退出:功能(路由器){
router.get('editContactController ).exitEditing();
}
})
})* /
})
});
}
);

编辑#2



我更改了现在路由器如下,但是它并没有做任何事情。

  define('routes / apps_router',['ember'], 
function(){
return Em.Router.extend({
enableLogging:true
,location:'hash'

,map:function匹配){
match(/)。to(CategoryList,function(match){
match(/)。to(mainNavigation);
});
}

,root:Ember.Route.extend({
index:Ember.Route.extend({
route:'/'

,renderTemplates:function(){
this.render('mainNavigation',{
into:'CategoryList'
});
}
// ....
});
}
);

亲切问候,
Christopher

解决方案

如果您使用最新版本的ember与v2路由器,您可以这样做:

  App.Router.map(function(match){
match(/)。to(categoryList,function ){
match(/)。to(foo);
});
});

在你的catergoryList模板中,放一个{{outlet}}(你可以选择命名) p>

然后,您要插入到catergoryList的模板的路由将如下所示:

 code> App.fooRouter = Ember.Router.extend({
renderTemplates:function(){
this.render('foo',{
into:'catergoryList'
});
}
})

一个很好的例子在实践中可以在这里找到: https://github.com/sh4n3d4v15/ember-todos


I'm playing around with ember.js and am stuck somehow finding out how to build up the structure the right way. I could follow all examples, but have some problems putting them all together.

I'm using require.js and handlebars.

My directory structure looks like this:

- app
- - controllers
- - css
- - helpers
- - lib
- - models
- - routes
- - templates
- - - partials
- - views

My application.js looks like this:

require.config({
    paths:{
        jquery:'lib/jquery-1.7.2',
        handlebars:'lib/handlebars',
        ember:'lib/ember',
        ember_data:'lib/ember-data',
        text:'lib/requireJS/text',
        md5:'lib/md5',
        spin:'lib/spin'
    },

    shim:{
        'ember':{
            deps:[ 'jquery', 'handlebars'],
            exports:'Ember'
        },
        'ember_data':{
            deps:[ 'ember'],
            exports:'DS'
        }
    },

    waitSeconds:15        
});

define('application'
        ,[
            // Routes
            'routes/app_router'

            // Controller
            ,'controllers/application_controller'

            // Views
            ,'views/application_view'
            ,'views/category/category_list_view'

            // Libraries
            ,'jquery'
            ,'handlebars'
            ,'ember'
            ,'ember_data'
            ,'spin'

        ]
        , function (

             // Router
             Router

             // Controller
            ,ApplicationController

             // Views
            ,ApplicationView
            ,CategoryListView

             // Models
            ,Category
            ,Product
        )
    {
        return  Ember.Application.create({

             VERSION: '1.0.0'

            ,rootElement:'#main'

            // Load Router
            ,Router:Router

            // Load Controllers
            ,ApplicationController:ApplicationController

            // Load associated Views
            ,ApplicationView:ApplicationView
            ,CategoryListView:CategoryListView

            // Load Models
            ,Category:Category
            ,Product:Product

            //Persistence Layer,using default RESTAdapter in ember-data.js.
            ,store:DS.Store.create({
                revision:10
                ,adapter:DS.RESTAdapter.create({
                     bulkCommit:false
                    ,serializer:DS.Serializer.create({
                        primaryKey:function (type) {
                            return type.pk;
                        }
                    })
                    ,mappings:{
                        //categories:Category
                    }
                    ,namespace:'api'
                    ,url: "https://example.org"
                })
            })

            ,ready:function () {

            }
        });
    }
);

Then my application controller

define(
    'controllers/application_controller'
    ,['ember' ],
    function () {
        return Ember.Controller.extend({
            init: function() {
            }
        });
    }
);

The application view:

define('views/application_view', [
        'text!templates/application.html',
        'ember'
    ],
    function(Application_markup) {
        return Ember.View.extend({
            template: Ember.Handlebars.compile( Application_markup ),
            elementId: 'container',
            didInsertElement: function() {
                this.$().hide().show("slow");
            }
        });
    }
);

And, finally, the application.html template

<div id="container">

    <div id="header">
        FOO BAR
    </div>

    <div id="navigation">
        {{outlet mainNavigation}}
    </div>

    <div id="content">

    </div>

    <div id="footer">

    </div>

</div>

What I am trying to do now is to include another template into the main application template (category_list). I guess I either have to do this in the HTML template itself, or in the application view - but in case of the latter one I don't know how to configure/parse/bind more than one template.

What is the best practice of building individual, independent, modular templates and to put them all together? Where exactly should this happen? Or is this even a wrong approach of using ember.js?

Maybe one of you could make some things more clear to me. Thanks.

EDIT #1

app_router.js

define('routes/app_router',
    ['ember' ],
    function () {
        return  Em.Router.extend({
            enableLogging:true, //useful for development
            /*  location property:  'hash': Uses URL fragment identifiers (like #/blog/1) for routing.
             'history': Uses the browser's history.pushstate API for routing. Only works in modern browsers with pushstate support.
             'none': Does not read or set the browser URL, but still allows for routing to happen. Useful for testing.*/
            location:'hash',
            /*   location: 'history',
             rootURL:'/app',*/
            root:Ember.Route.extend({
                index:Ember.Route.extend({
                    route:'/'

                    /*,connectOutlets:function (router) {
                        //Render application View ,sign in.
                        v = router.get('applicationController').get('view');
                        if (v) v.remove();
                        App.router.get('applicationController').set('loggedin', false);

                        router.get('applicationController').connectOutlet({name:'login', outletName:'loginform'});
                        router.get('loginController').enterLogin();

                    }*/
                })
                /*,contacts:Em.Route.extend({
                    route:'/contacts',

                    showContact:function (router, event) {
                        router.transitionTo('contacts.contact.index', event.context);
                    },

                    showNewContact:function (router) {
                        router.transitionTo('contacts.newContact', {});
                    },
                    logout:function (router) {

                        jQuery.ajax({
                            url:'/site/logout',
                            type:'POST',
                            success:function (response) {
                                if (!response.authenticated) {
                                    router.get('applicationController').set('loggedin', false).get('view').remove();
                                    router.transitionTo('root.index', {});
                                }
                            }
                        })
                    },


                    index:Em.Route.extend({
                        route:'/',
                        connectOutlets:function (router) {
                            if (router.get('applicationController').get('loggedin'))
                                router.get('applicationController').connectOutlet('contacts', App.store.findAll(App.Contact));
                            else   router.transitionTo('root.index');
                        }
                    }),

                    contact:Em.Route.extend({
                        route:'/contact',
                        index:Em.Route.extend({
                            route:'/:contact_id',
                            deserialize:function (router, urlParams) {
                                return App.store.find(App.Contact, urlParams.contact_id);
                                debugger;
                            },

                            showEdit:function (router) {
                                router.transitionTo('contacts.contact.edit');
                            },

                            connectOutlets:function (router, context) {
                                if (router.get('applicationController').get('loggedin'))
                                    router.get('contactsController').connectOutlet('contact', context);
                                else   router.transitionTo('root.index');
                            }
                        }),

                        edit:Em.Route.extend({
                            route:'edit',

                            cancelEdit:function (router) {
                                router.transitionTo('contacts.contact.index');
                            },

                            connectOutlets:function (router) {
                                if (router.get('applicationController').get('loggedin')) {
                                    var contactsController = router.get('contactsController');
                                    contactsController.connectOutlet('editContact', router.get('contactController').get('content'));
                                    router.get('editContactController').enterEditing();
                                } else     router.transitionTo('root.index');
                            },

                            exit:function (router) {
                                router.get('editContactController').exitEditing();
                            }
                        })
                    }),
                    newContact:Em.Route.extend({
                        route:'/contacts/new',

                        cancelEdit:function (router) {
                            router.transitionTo('contacts.index');
                        },

                        connectOutlets:function (router) {
                            if (router.get('applicationController').get('loggedin')) {
                                router.get('contactsController').connectOutlet('editContact', {});
                                router.get('editContactController').enterEditing();
                            } else     router.transitionTo('root.index');
                        },

                        exit:function (router) {
                            router.get('editContactController').exitEditing();
                        }
                    })
                })*/
            })
        });
    }
);

EDIT #2

I changed the router now as follow, but it does not do anything.

define('routes/apps_router', ['ember'],
    function () {
        return Em.Router.extend({
            enableLogging:true
            ,location:'hash'

         ,map: function (match) {
            match("/").to("CategoryList", function (match) {
                match("/").to("mainNavigation");
            });
        }

        ,root:Ember.Route.extend({
            index:Ember.Route.extend({
                route:'/'

                ,renderTemplates: function() {
                    this.render('mainNavigation', {
                        into: 'CategoryList'
                    });
                }
           // ....
        });
    }
);

Kind regards, Christopher

解决方案

if you use the latest release of ember with v2 router, you can do something like this:

App.Router.map(function (match) {
    match("/").to("categoryList", function (match) {
        match("/").to("foo");
    });
});

In your catergoryList template, put an {{outlet}} (you can optionally name it)

Then, your route for the template you want to insert into catergoryList will be like this:

App.fooRouter = Ember.Router.extend({
renderTemplates:function () {
        this.render('foo', {
            into:'catergoryList'
        });
    }
})

A good example of this in practice can be found here: https://github.com/sh4n3d4v15/ember-todos

这篇关于Ember.js - 正确的(结构,包括,一般问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆