Ember CLI、ember 套接字和咖啡脚本
我只使用 Ember 大约一个月,所以不能保证这是最好的方法,但我必须使用 Socket.io 和 Ember Data 建立一个 Ember CLI 项目。以下内容基于我的工作代码,尽管以下内容未经测试。我认为你需要完成 99% 的一切都在这里。祝您故障排除!
.jshintrc - 如果您在此处不包含 EmberSockets,Ember 服务将会对您大喊大叫
{
"predef": {
"document": true,
"window": true,
"nameofprojectENV": true,
"EmberSockets": true
},
...
}
Brocfile.js - 导入 Ember 套接字
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var app = new EmberApp();
// change this path to where ember-sockets.js is
app.import('vendor/ember-sockets/package/ember-sockets.js');
module.exports = app.toTree();
app.js - 记得用实际项目名称替换 nameofproject
import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
Ember.MODEL_FACTORY_INJECTIONS = true;
// every controller using ember sockets must be listed here in the controllers array
var Socket = EmberSockets.extend({
host: 'example.local',
port: 8080,
controllers: [
'example'
// more controllers here
]
});
var App = Ember.Application.extend({
modulePrefix: 'nameofproject',
Resolver: Resolver,
Socket: Socket
});
loadInitializers(App, 'nameofproject');
export default App;
router.coffee - 记得用实际项目名称替换 nameofproject
`import Ember from 'ember'`
Router = Ember.Router.extend
location: nameofprojectENV.locationType
Router.map ->
@route 'example'
`export default Router`
模型/example.coffee
`import DS from 'ember-data'`
Example = DS.Model.extend
name: DS.attr('string')
`export default Example`
路线/example.coffee
`import Ember from 'ember'`
ExampleRoute = Ember.Route.extend
# set model to be all example records
model: ->
@store.all('example')
setupController: (controller, model) ->
controller.set('model', model)
`export default ExampleRoute`
控制器/example.coffee
`import Ember from 'ember'`
ExampleController = Ember.Controller.extend
#### properties
examples: (->
# @get('content') gets the model, which in this case, is example (set in route)
@get('content')
).property('content') # watching the model like this might not be right?
#### methods
getExamples: ->
@socket.emit 'pub',
# whatever data you need to pass to the server
data : {examples: true}
# name of the event you want the data returned on
event: "getExamples"
#### sockets
sockets:
# returns examples from server
getExamples: (data) ->
# log the data for fun, also to see that you are getting data back
console.log data
# set controller to @, which is the same as this.
controller = @
# get your array of examples from JSON returned from server
examples = data.examples
examples.forEach (example) ->
# controller instead of @, or it doesn't work
controller.store.push 'example',
# you need ids or this will not work
id: example.id
name: example.name
`export default ExampleController`
模板/example.coffee
{{#each example in examples}}
{{example.id}} {{example.name}}
{{/each}}
<button {{action getExamples}}>Get Examples</button>
我建议使用Chrome Ember Inspector进行故障排除。您还可以查看您的数据模型和记录等。