Comments (9)
Sounds good!
We should check parent_tag and if it's dirty push them to the server than push changed item on success, right?
from backbone-offline.
Смотри, допустим я в оффлайне создал теги a, b, c, при этом a.parent_tag=b, b.parent_tag=c, они находятся в одной коллекции. Потом делаю push, он сразу делает pushItem для всех элементов, получается что a и b получают parent_tag_id=0 вместо правильных b.id, c.id соответственно.
Я предлагаю:
в pushItem мы находим предков высшего уровня (тех, у которых parent_tag_id не локальный), то есть, в данном случае – с, потом on success b, потом on success a – рекурсивно.
Но можно и как ты предлагаешь - брать все подряд элементы и смотреть, является ли parent_tag_id локальным, и в таком случае сначала делать pushItem для предка, а собственно элемент – on success. Но в этом случае придётся сделать так, чтобы элементы не сохранялись дважды - неправильно и правильно.
Причем таких полей может быть много, например, БД людей с разными типами отношений между людьми. Таким образом будет например поле mother_id, father_id, которые ссылаются в ту же коллекцию и т.д.
Надеюсь, понятно изъясняюсь. Я не очень глубоко разбирался в исходниках, поэтому не знаю, какой подход будет лучше.
from backbone-offline.
Ok, thank you! I understand your example ;) My and your method are in a similar way.
from backbone-offline.
This simple patch is for the my case of 1 field. Also it's not clear how to sync several collections at one time with a server if we have asynchronous requests, so the second collection also can have dirty fields when we make push() for it, am I right? So we need success linking of all dirty models? To make dirty models to wait for the setting of the key fields. And to make sure, that all the "dirty fields" are set before we push it to the server.
initialize: ->
@storage = new Offline.Storage('blocks', this, keys: {parent_id: this})
@storage.sync.pushItem= (item,options={}) ->
return if /^\w{8}-\w{4}-\w{4}/.test(item.get("parent_id")) && !options.skipCheck?
@storage.replaceKeyFields(item, 'server')
localId = item.id
delete item.attributes.id
[method, item.id] = if item.get('sid') is 'new' then ['create', null] else ['update', item.attributes.sid]
this.ajax method, item, success: (response, status, xhr) =>
item.set(sid: response.id) if method is 'create'
item.save {dirty: false}, {local: true}
@pushItem(i, skipCheck: true) for i in item.children()
from backbone-offline.
Thank you @ulitiy for your patch! I will think about this problem and try to fix it as soon as possible.
from backbone-offline.
You can't universally solve this task without double saving, because there is at least a problem with cycling referencing (ex. a.brother_id=b.id, b.brother_id=a.id). So the simplest way is to save all models, then save second time all models, that have updated key fields due to replaceKeyFields.
from backbone-offline.
Monkey patch with double saving if it's necessary
Offline.Storage.prototype.replaceKeyFields= (item, method) ->
if Offline.onLine()
item = item.attributes if item.attributes
for field, collection of @keys
replacedField = item[field]
if !/^\w{8}-\w{4}-\w{4}/.test(replacedField) or method isnt 'local'
newValue = if method is 'local'
wrapper = new Offline.Collection(collection)
wrapper.get(replacedField)?.id
else
ref_item=collection.get(replacedField)
if ref_item?
item.dirty=true #added
ref_item.get('sid')
item[field] = newValue unless _.isUndefined(newValue)
return item
Offline.Sync.prototype.push= (options)->
window.inPush=0 #added
this.pushItem(item,options) for item in @collection.dirty()
this.flushItem(sid) for sid in @storage.destroyIds.values
Offline.Sync.prototype.pushItem= (item,options) ->
@storage.replaceKeyFields(item, 'server')
localId = item.id
delete item.attributes.id
[method, item.id] = if item.get('sid') is 'new' then ['create', null] else ['update', item.attributes.sid]
window.inPush++ #added
this.ajax method, item,
success: (response, status, xhr) =>
item.set(sid: response.id) if method is 'create'
item.save {dirty: false}, {local: true}
window.inPush-- #added
if inPush==0 #added
@push inner_success: options?.success #added, to make chain collection pushes: push tags-on success->push posts
options?.inner_success?() #added
But the weakness is to ensure, we have only one sync run, because of global inPush variable
from backbone-offline.
@ulitiy thanks for your activity ;) You can pull request your code ;)
And If you using this library we be able to discuss it in skype. My name is alekseys.kulikov
from backbone-offline.
@ulitiy I added a simple guide for contributors https://github.com/Ask11/backbone.offline#how-to-contribute
It will be great if you will put your patch as pull request.
from backbone-offline.
Related Issues (20)
- Fetch a simple Model ? HOT 4
- Fetch Local dont work with Backbone 1.0 HOT 4
- Bug with Storage#clear
- Collection is empty on fetching. Errors on POST request. HOT 5
- "Record Not Found" when fetching a model HOT 2
- Backbone.js offline not saving to local storage after fetch HOT 1
- error on fetch/pull HOT 3
- Backbone 1.0 and Backbone 0.9.10 compatibility difference
- Server implementation HOT 3
- Creates duplicate records if id is string HOT 1
- Option to use mongo objectid generator
- sync.push error
- collection.storage.sync.push() issue
- id not sent with this.model.save() HOT 1
- want to track the count of un-synced HTTP CRUD events
- Duplicate Add Event HOT 2
- delete que is never empty HOT 1
- Need help with updating related keys in multiple collections
- .storage.sync.full() alle Model data gets dirty HOT 1
- Using backbone-offline in conjuction with backbone.iobind?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from backbone-offline.