Last active
August 29, 2015 13:55
-
-
Save knyga/8730781 to your computer and use it in GitHub Desktop.
Mizzle - получить список товаров со страницы агрегатора или категорий
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Product = function($dom) { | |
this.id = /\/product\/(\d+)/.exec($dom.find('a:last').attr('href'))[1]; | |
this.name = $dom.find('a:last').text(); | |
this.href = $dom.find('a:last').attr('href') | |
if (this.href.indexOf('http') < 0) { | |
this.href = "http://mizzle.ru" + this.href; | |
} | |
}; | |
Product.prototype.toString = function() { | |
return this.id + "\t" + this.href + "\t" + this.name; | |
}; | |
var ProductCollection = function(options) { | |
if("undefined" === typeof options) { | |
options = {}; | |
} | |
this.list = []; | |
this.url = options.url || location.href; | |
this.pageCount = options.pageCount || 1; | |
this.timeout = options.timeout || 5000; | |
this.pattern = options.pattern || '.multilist li, .subproduct-table tr'; | |
}; | |
ProductCollection.prototype.grabPagesAsync = function(callback) { | |
var that = this; | |
var timeoutId; | |
for (var id = 1; id <= this.pageCount; id++) { | |
$.get(that.url + '?page=' + id, function(data) { | |
that.parsePage.call(that, data); | |
console.log(that.list.length); | |
clearTimeout(timeoutId); | |
setTimeout(function() { | |
if ("function" === typeof callback) { | |
callback(); | |
} | |
console.log('done with ' + that.list.length); | |
}, that.timeout); | |
}); | |
} | |
}; | |
ProductCollection.prototype.grabCurrentSync = function() { | |
this.parsePage($('body').html()); | |
}; | |
ProductCollection.prototype.parsePage = function(data) { | |
var that = this; | |
$(this.pattern, data).each(function(i) { | |
that.list.push(new Product($(this))); | |
}); | |
}; | |
ProductCollection.prototype.clear = function() { | |
this.list = []; | |
}; | |
ProductCollection.prototype.toTable = function() { | |
return this.list.join('\n'); | |
}; | |
//////////////////////// | |
//Чтение со страницы агрегатора (вариант использования) | |
var collection = new ProductCollection(); | |
collection.grabCurrentSync(); | |
console.log(collection.toTable()); | |
//Чтение со страниц категории (вариант использования) | |
var collection = new ProductCollection({ | |
url: 'http://mizzle.ru/game/1/wow', | |
pageCount: 8 | |
}); | |
collection.grabPagesAsync(function() { | |
console.log(collection.toTable()); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment