Rya*_*yan 12 javascript ruby-on-rails vue.js
我喜欢像Firebase这样的实时数据库是他们的推送功能.例如,vuefire使得自我更新对象变得异常简单,而无需串联数百个套接字侦听器和回调.
这是一个例子:
data(){
return {
books: []
}
},
created(){
axios.get('/books', (books) => {
this.books = books
})
}
Run Code Online (Sandbox Code Playgroud)
为了向此添加db反应,我需要至少3个事件"book-created","book-updated","book-removed".
Pusher.on('book-created', (book) {
this.books.push(book)
})
Pusher.on('book-updated', (book) {
let b = _.find(this.books, {id: book.id})
if(b){
_.extend(b, book)
}
})
etc..
Run Code Online (Sandbox Code Playgroud)
当你有很多模型和很多视图时,它会变得很毛茸茸,有些视图有不同的书籍,所以我不能只有一本标准的书籍vuex变量.有没有合理/快速的方法来解决这个问题?
我当然可以抽象我在后端发送的事件,这样我所有的模型都会自动推送事件.但是前端是我感到困惑的地方.
我之前从未使用过pusher,而且我不确切地知道你所指的"不同的书籍"究竟是什么,但我想我可以给你一些起点让你的代码看起来更优雅.
我建议的第一件事; 不要试图重新发明轮子,使用组件mixins.只需创建一个mixin,就像你通常使用你的后端一样,让它与一些动态选项(你可以在组件中设置data())一起工作,并将它导入到你需要相同功能的每个组件上,并有不同的选项.
示例(您需要相应地调整它)
// Create an ES6 module and export this function, or the whole mixin
// (in that case export the mixin instead)
const initPusher = function ({pusher, collection, key, events}, component) {
collection = component[collection]
pusher.on(events.created, (record) => {
collection.push(record)
})
pusher.on(events.updated, (record) => {
let r = _.find(collection, {[key]: record[key]})
if(r){
_.extend(r, record)
}
})
}
const PusherMixin = {
methods: {
// You can add some common methods for all your
// components making use of this mixin
},
created () {
initPusher(Object.assign({}, {
pusher: Pusher,
collection: 'collection',
key: 'id',
events: {
created: 'book-created',
updated: 'book-updated'
}
}, this.pusherOptions), this)
}
}
new Vue({
el: "#app",
mixins: [PusherMixin],
data () {
return {
books: [],
pusherOptions: {
collection: 'books',
key: 'id',
events: {
created: 'book-created',
updated: 'book-updated'
}
}
}
}
})
Run Code Online (Sandbox Code Playgroud)
我的第二个建议暗示了一个带有一些自定义方法和钩子的操作数组原型来触发事件和XHRequests但是在完成mixin的代码之后,我发现用更多方法扩展数组的原型会增加太多的复杂性,而且一个好的mixin是完全相反.
如果你想更深入,你可能想看看RxJS和observables.您可以使用Pusher在其上构建一些内容,以获得类似Firebase实时对象的内容.
| 归档时间: |
|
| 查看次数: |
264 次 |
| 最近记录: |